objc-zen/objc-zen-book

Assigning self in init

ole opened this issue · 2 comments

ole commented

You wrote:

The interesting part is that the init implementation of NSObject is simply returning self, this is because the variable self is written after the alloc method where all the initialization logic is done.

I think this is not correct or at least confusing. There is nothing special happening between alloc and init that causes “the variable self is written after the alloc method”. alloc simply returns a pointer to the memory it allocated. By sending any message (init or not) to this pointer, objc_msgSend() assigns it to self in the context of the method that was called.

This is also needed to allow the NSObject's subclass to follow the previously exposed pattern.

I donʼt understand what you mean by this sentence.

There is another important part of the contract with init: the method can (and should) signal to the caller that it wasn't able to successfully finish the initialization by returning nil;

Correct. There is another reason why self = [super init] is necessary. Initializers are allowed to return a different instance than the one they have been called on. This is done by re-assigning self in the initializer. Some Cocoa classes use this to return the same instance for identical (immutable) objects. For example, allocating two NSNumbers with the same value (say, @3.14 and @3.14) will return the same instance (ignoring tagged pointers for the moment).

ole commented

I see you're using this pattern in the discussion of class clusters already. I think it warrants at least a note in the section about initializers, as well.

Thanks @ole for you feedback.

I understand your confusion about

the variable self is written after the alloc method

and probably we phrased incorrectly.

We don't meant that something magic is happening between the alloc and init but rather that after alloc work is completed, that as you said, is to allocate the memory; self has a value in the context of every method call. Definitely the use of the verb "writing" is not correct. The thing is that we realized that a lot of developers have no clear idea about how this two-step process actually works (some of them don't even realise that alloc is returning the pointer to the allocated object).

Regarding

This is also needed to allow the NSObject's subclass to follow the previously exposed pattern.

it was to reinforce the consistency in apply the pattern:

self = [super init]
if (self) {
}
return self;

Honestly now that you point it out it seems definitely not clear, redundant a probably misleading.