Objective-c:关于self = [super init]的问题 [英] Objective-c: Questions about self = [super init]

查看:114
本文介绍了Objective-c:关于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];




  1. [MyClass alloc] 分配一个 MyClass 的实例。

  2. init 消息是发送到此实例以完成初始化过程。

    在该方法中, self (这是所有Objective-C方法的隐藏参数)是
    步骤1中分配的实例。

  3. [super init] 调用超类实现 init 使用相同的(隐藏的)
    self 参数。
    (这可能是你错误理解的一点。)

  4. init 方法 BaseClass self 仍然是同一个实例 MyClass
    这个超类init方法现在可以

  1. [MyClass alloc] allocates an instance of MyClass.
  2. 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.
  3. [super init] calls the superclass implementation of init with the same (hidden) self argument. (This might be the point that you understood wrongly.)
  4. In the init method of BaseClass, self is still the same instance of MyClass. This superclass init method can now either


  • self 并返回 self ,或

  • 放弃 self 并分配/初始化并返回一个不同的对象。

  • Do the base initialization of self and return self, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆