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;
NSLog(@"%@",self);
}
…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):
cocoawithlove.com/2009/04/wh … super.html
mikeash.com/pyblog/the-how- … izers.html