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.