Objective-c: Questions about self = [super init]
Assuming that MyClass
is a subclass of BaseClass
, the following happens whenyou call
MyClass *mc = [[MyClass alloc] init];
[MyClass alloc]
allocates an instance ofMyClass
.- The
init
message is sent to this instance to complete the initialization process.
In that method,self
(which is a hidden argument to all Objective-C methods) isthe allocated instance from step 1. [super init]
calls the superclass implementation ofinit
with the same (hidden)self
argument.(This might be the point that you understood wrongly.)In the
init
method ofBaseClass
,self
is still the same instance ofMyClass
.This superclass init method can now either- Do the base initialization of
self
and returnself
, or - Discard
self
and allocate/initialize and return a different object.
- Do the base initialization of
Back in the
init
method ofMyClass
:self = [super init]
is now either- The
MyClass
object that was allocated in step 1, or - Something different. (That's why one should check and use this return value.)
- The
- The initialization is completed (using the
self
returned by the superclass init).
So, if I understood your question correctly, the main point is that
[super init]
calls the superclass implementation of init
with the self
argument,which is a MyClass
object, not a BaseClass
object.
As you have Question self = [super init]
in the if Condition suggest a specific meaning.
First of all [super init]
gives the initialization of the superclass of the existing class which is in use currently. Using [super init]
gives the super class initialization which shows that object exist of the class.
Now when you use self = [super init]
that means you are assigning the class to the self for the further utilization of the same class.
And at the end you put it in if condition as if(self = [super init])
this means you are checking whether the object of the class exist of not to prevent the foul behavior of the application.
I think it is clear now!!!
@MartinR has a very good answer. But do you ever wonder why "[super init] calls the superclass implementation of init with the same (hidden) self argument. (This might be the point that you understood wrongly.)" works in his 3rd point ?
Here is the excerpt from Big Nerd Ranch guide 3rd edition, chapter 2 Objective C that clarifies this point
“How does super work? Usually when you send a message to an object, the search for a method of that name starts in the object’s class. If there is no such method, the search continues in the superclass of the object. The search will continue up the inheritance hierarchy until a suitable method is found. (If it gets to the top of the hierarchy and no method is found, an exception is thrown.)”
“When you send a message to super, you are sending a message to self, but the search for the method skips the object’s class and starts at the superclass.”
This code shows how iOS Runtime performs this task
objc_msgSendSuper(self, @selector(init));