Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 786
user4951 Avatar asked Apr 14 '11 17:04

user4951


1 Answers

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:

  • http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
  • Inheritance diagram: http://www.sealiesoftware.com/blog/class%20diagram.pdf
  • http://cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html
like image 98
Daniel Dickison Avatar answered Sep 26 '22 19:09

Daniel Dickison