What's the Point of Using [self class] What's the Point of Using [self class] xcode xcode

What's the Point of Using [self class]


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:


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.