What's the Point of Using [self class]

user4951 picture user4951 · Apr 14, 2011 · Viewed 10.8k times · Source

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 +)

Answer

Sherm Pendley picture Sherm Pendley · Apr 14, 2011

It's to support subclassing. If you hard-coded the class name, as in [[Vehicle alloc] init], then a subclass of Vehicle would have to override +vehicleWithColor: to make it do the right thing. With [self class], you could create a subclass HarleyDavidson, and [HarleyDavidson vehicleWithColor:[NSColor blackColor]] would do the right thing automatically, creating an instance of HarleyDavidson instead of an instance of Vehicle.

(Edit:)

See Joe's comment below concerning self vs. [self class] in class methods - In class methods, it doesn't make a difference. But there is a situation where it can. Classes can respond to instance methods that are defined in a root class - -class itself is just such a method, defined as an instance method in the NSObject protocol. So if you extend a root class such as (for example) NSObject by adding an instance method, that method should always use [self class] if it needs to refer to its own Class object.