Search code examples
objective-cxcodeclassself

What's the Point of Using [self class]


Is this code correct

@implementation Vehicle
+(id) vehicleWithColor:(NSColor*)color {
    id newInstance = [[[self class] alloc] init]; // PERFECT, the class is // dynamically identified
    [newInstance setColor:color];
    return [newInstance autorelease];
}
@end

Why use [self class]

I thought self already points to the class on static methods (the ones with +)


Solution

  • You're right: [self class] is unnecessary in a class method (it's more commonly called that in Objective-C rather than "static" method), because self is already a class, and [self class] returns itself.

    But it gets a bit more interesting. In Objective-C, class objects are technically instances of metaclasses. So [self class] in a class method ought to return the metaclass instead of the class itself. But for practical purposes, Objective-C hides the metaclass so it handles this case specially.

    Some good reading on this topic: