Objective-c:关于self = [super init]的问题 [英] Objective-c: Questions about self = [super init]
问题描述
我在init方法中看到过 self = [super init]
。我不明白为什么。不会 [super init]
返回超类?如果我们指向 self = [super init]
,我们是否得到 self = superclass
?
这是一个示例代码片段
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.
推荐答案
假设 MyClass
是 BaseClass
,当您拨打
时会发生以下情况
Assuming that MyClass
is a subclass of BaseClass
, the following happens when
you call
MyClass *mc = [[MyClass alloc] init];
-
[MyClass alloc]
分配一个MyClass
的实例。 -
init
消息是发送到此实例以完成初始化过程。
在该方法中,self
(这是所有Objective-C方法的隐藏参数)是
步骤1中分配的实例。 -
[super init]
调用超类实现init
使用相同的(隐藏的)
self
参数。
(这可能是你错误理解的一点。) -
init
方法BaseClass
,self
仍然是同一个实例MyClass
。
这个超类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) is the 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
- 做
self $ c $的基本初始化c>并返回
self
,或 - 放弃
self
并分配/初始化并返回一个不同的对象。
- Do the base initialization of
self
and returnself
, or - Discard
self
and allocate/initialize and return a different object.
返回 init
方法 MyClass
: self = [super init]
现在是
- 在步骤1中分配的
MyClass
对象,或 - 不同的东西。 (这就是人们应该检查并使用此返回值的原因。)
- The
MyClass
object that was allocated in step 1, or - Something different. (That's why one should check and use this return value.)
所以,如果我理解你的问题,主要的一点是
So, if I understood your question correctly, the main point is that
[super init]
使用 self $调用
init
的超类实现c $ c>参数,
这是一个 MyClass
对象,而不是 BaseClass
对象。
calls the superclass implementation of init
with the self
argument,
which is a MyClass
object, not a BaseClass
object.
这篇关于Objective-c:关于self = [super init]的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!