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 +)
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With