Weird init method


In the book the code shows that we override the init method

I do have one question here, there is no object to instantiate and it is just calling the original init method of NSObject.
How could we initialize it?
Like when we normally initialize object

I mean how could we initialize object when it wasn’t instantiated at the first place like this unless it was instantiated earlier

Now in this method we are calling init through super

where there are no object to intialized, and you are assigning it to self some more.

I still have no idea how to think like a programmer.
Like how does all this method fit to replace the original init method.


Our usage of “self = [super init]” is perhaps one of the most awkward and unintuitive things that we do in Mac/iOS development. Don’t let this frustrate you- it’s even hard to /explain/, let alone understand.

The key is in remembering that self is a local variable. It’s not special in any way except that it exists without us declaring it. It’s already there. Any time a method begins, a local variable called self exists and its initial value is the memory address of the object that’s executing the method. Like any local variable, you can change its value. Changing the value of the self variable in one method doesn’t affect any other methods, or even future runs of the same method.

Case in point, if I were to have a class called BNRFoo with method that looks like this:

- (void)someMethod
    NSDate *someDate = [NSDate date];
    self = someDate;

…the result is that the NSDate object will be logged, not the BNRFoo object that’s actually running the code. Nothing at all has happened to the BNRFoo object running the code. The next time this (or any other BNRFoo method) runs, self will start out being a pointer to the BNRFoo object itself.

So, when we say “self = [super init]”, we’re merely temporarily changing the value of a local variable like any other.

The next bit to understand is the meaning of the keyword super. Unlike self, super is not a variable. It’s a keyword that’s meant to be used as the receiver of a message. When used as the receiver of a message, the message is actually sent to self, but the superclass’ implementation of the method is used instead of self’s own implementation. It may be worth having another look at the Inheritance chapter’s discussion of super.

What we’re doing here is making sure that, if our superclass’ -init method returns a new object, we continue setting up /that/ object in our init method rather than the originally allocated object. This feels very weird and awkward and is not without its own share of problems (see links below), but this has become the standard of how we write our init method.

External links discussing this business (warning, very technical discussions): … super.html … izers.html


Thanks for that discussion of “self”. That’s very helpful and not stated so explicitly n the book.