I’m reading through Mark Dalrymple’s Learn Objective-C on the Mac (only at the chapter on Protocols, so still relatively newbish) and trying to figure something out:
Why would you ever reference a class by its own name? If I had a class called Foo, why would I ever want to write, say,
[[Foo alloc] init]
and not
[[[self class] alloc] init]
If I had a subclass Bar, wouldn’t the first option invalidate me from writing
[[Bar alloc] init]
whereas the second option would allow it? When would the first option be better?
Generally, within a class method, you do use
[[self alloc] init]. For example, the canonical way to write a convenience method for a class is:(Note that in a class method,
selfrefers to the class object.)However, you would use
[[Foo alloc] init](that is, an explicit class name) if you actually want an instance of theFooclass (and not a subclass).