我为什么要称呼self = [super init] [英] Why should I call self=[super init]

查看:69
本文介绍了我为什么要称呼self = [super init]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了我的类及其init方法.为什么要调用并返回分配给self的超类init的值?它涵盖哪些情况?

Let's say I create my class and its init method. Why should I call and return value of superclass init assigned to self? Which cases it covers?

我很欣赏为什么可可超类和非可可类需要它的例子.

I would appreciate examples why would I need it for Cocoa superclass and non-Cocoa.

推荐答案

您是说为什么

self = [super init];

而不是

[super init];

两个原因:

  1. 在初始化中,失败通过返回nil来指示.您需要知道超级对象的初始化是否失败.
  2. 超类可能选择用另一个对象替换+ alloc返回的自我.这种情况很少见,但最常见于类群集.

根据Michael的评论进行

Edited in response to Michael's comment:

我可以理解为什么我需要保存并返回[super init].但这仅仅是约定俗成,好看让我们将self作为一个临时变量来传递结果吗?

I can understand why I need to save and return [super init]. But is it just convention and good looking makes us use self as a temporary variable to pass result along?

不.实例变量是相对于self指针访问的,因此在下面:

No. Instance variables are accessed relative to the self pointer, so in the following:

-(id) init
{
    self = [super init];
    if (self != nil)
    {
        myBoolIvar = YES; 
       // The above is an implicit version of self->myBoolIvar = YES;
    }
    return self;
}

显然,自己必须指向正确的内存块,即您要返回的内存块.

self has clearly got to point to the right block of memory i.e. the one you are going to return.

另一点是,如果super init返回不同的类实例,则该行之后的其余代码甚至可能没有意义,从而导致内存泄漏和崩溃,甚至没有谈论从该类实例化的对象.

The other point is that if super init returns different class instance then the rest of the code after that line may not even make sense, lead to memory leaks and crashes, not even talking about the object instantiated from that class.

那可能是个问题.如果我将NSNumber子类化,并且[super init]决定返回一个NSString(它可以-没有阻止它的方法),那显然是一场灾难.从-init的超级返回中,无论是为ivars提供空间并可以进一步细分为子类,都必须与子类兼容",否则,这是一个可怕的bug(当然,除非记录了问题).因此,一般而言,您无需担心检查类.但是,请务必阅读文档.例如,请参阅NSString文档中有关将NSString继承的部分.

That could be a problem. If I subclassed NSNumber and [super init] decided to return an NSString (which it could - there's nothing to stop it) that would clearly be a disaster. Whatever super returns from -init must be "compatible" with the subclass in the sense of providing space for ivars and being further subclassible or it's a horrendous bug (unless, of course, the problem is documented). So, in general, you don't need to worry about checking the class. However, do read the documentation. See for instance the section on subclassing NSString in NSString's docs.

这篇关于我为什么要称呼self = [super init]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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