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
From Apple's Documentation:
Because an init... method might return nil or an object other than the one explicitly allocated, it is dangerous to use the instance returned by alloc or allocWithZone: instead of the one returned by the initializer. Consider the following code:
id myObject = [MyClass alloc];
[myObject init];
[myObject doSomething];
The init method in the example above could have returned nil or could have substituted a different object. Because you can send a message to nil without raising an exception, nothing would happen in the former case except (perhaps) a debugging headache. But you should always rely on the initialized instance instead of the “raw” just-allocated one. Therefore, you should nest the allocation message inside the initialization message and test the object returned from the initializer before proceeding.
id myObject = [[MyClass alloc] init];
if ( myObject ) {
[myObject doSomething];
} else {
// error recovery...
}
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.