Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use [ClassName alloc] instead of [[self class] alloc]?

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?

like image 907
Nick Sweet Avatar asked Aug 24 '10 18:08

Nick Sweet


2 Answers

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:

+ (id)fooWithBar:(Bar *)aBar
{
    return [[[self alloc] initWithBar:aBar] autorelease];
}

(Note that in a class method, self refers to the class object.)

However, you would use [[Foo alloc] init] (that is, an explicit class name) if you actually want an instance of the Foo class (and not a subclass).

like image 74
mipadi Avatar answered Nov 19 '22 22:11

mipadi


You refer to a class by it's name whenever you want exactly that class. If a subclass was derived from that class, a self in the same method would represent that derived class instead. Hence, if you want to explicitly instantiate a superclass, this could be done.

There are occasions where this might make sense. Either to force the subclass to override the method in order to return an instance of it's class. Or to return a different class, like a placeholder object used in the creation of an NSArray etc.

like image 44
Max Seelemann Avatar answered Nov 19 '22 23:11

Max Seelemann