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
.
- 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) 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
- Do the base initialization of
self
and return self
, or
- Discard
self
and allocate/initialize and return a different object.
Back in the init
method of MyClass
: 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 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…