I'm from the C++ world so the notion of assigning this
makes me shudder:
this = new Object; // Gah!
But in Objective-C there is a similar keyword, self
, for which this is perfectly acceptable:
self = [super init]; // wait, what?
A lot of sample Objective-C code uses the above line in init
routines. My questions:
1) Why does assignment to self
make sense (answers like "because the language allows it" don't count)
2) What happens if I don't assign self
in my init
routine? Am I putting my instance in some kind of jeopardy?
3) When the following if
statement fails, what does it mean and what should I do to recover from it:
- (id) init { self = [super init]; if (self) { self.my_foo = 42; } return self; }
self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.
Why do we assign [super init] to self here? The textbook reason is because [super init] is permitted to do one of three things: Return its own receiver (the self pointer doesn't change) with inherited instance values initialized. Return a different object with inherited instance values initialized.
This is a topic that is frequently challenged by newcomers:
Basically, it stems from the idea that a superclass may have over-ridden the designated initializer to return a different object than the one returned from +alloc
. If you didn't assign the return value of super
's initializer into self
, then you could potentially be dealing with a partially initialized object (because the object that super
initialized isn't the same object that you're initializing).
On the whole, it's pretty rare for super
to return something different, but it does happen in a couple of cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With