I have seen self = [super init]
in init methods. I don't understand why. Wouldn't [super init]
return the superclass? And if we point self = [super init]
, are we not getting self = superclass
?
Here's an example code fragment
- (id)init { if (self = [super init]) { creationDate = [[NSDate alloc] init]; } return self; }
Hope someone can clarify this for me. Thank you.
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.
Super is self , but when used in a message expression, it means "look for an implementation starting with the superclass's method table."
In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).
Alloc allocates memory for the instance, and init gives it's instance variables it's initial values. Both return pointers to the new instance, hence the method chain.
Assuming that MyClass
is a subclass of BaseClass
, the following happens when you call
MyClass *mc = [[MyClass alloc] init];
[MyClass alloc]
allocates an instance of MyClass
.init
message is sent to this instance to complete the initialization process.self
(which is a hidden argument to all Objective-C methods) is the allocated instance from step 1.[super init]
calls the superclass implementation of init
with the same (hidden) self
argument. (This might be the point that you understood wrongly.)In the init
method of BaseClass
, self
is still the same instance of MyClass
. This superclass init method can now either
self
and return self
, orself
and allocate/initialize and return a different object.Back in the init
method of MyClass
: self = [super init]
is now either
MyClass
object that was allocated in step 1, orself
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.
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