iPhone - 当 [super init] 失败时使用 self = [super init]

标签 iphone objective-c inheritance initialization subclass

两者之间有什么区别:

// 1
-(id) init {
    self = [super init];
    if (self) {
        ... do init ....
    }
    return self;
}

// 2 - I guess it's exactly the same as previous
-(id) init {
    if (self = [super init]) {
        ... do init ....
    }
    return self;
}

// 3 - is this one a really bad idea and if yes, Why ?
-(id) init {
    self = [super init];
    if (!self) return nil;

    ... do init ....

    return self;
}

// 4 - I think this one sounds OK, no ? But what is returned... nil ?
-(id) init {
    self = [super init];
    if (!self) return self;

    ... do init ....

    return self;
}

编辑:添加感谢 Peter M。

// 5 - I really like the readability of this one
-(id) init {
    if(!(self = [super init])) return self;  // or nil

    ... do init ....

    return self;
}

最佳答案

它们都做同样的事情,但第一个是常用的,因为苹果建议

第二个很常用,但它会在新版本的 Xcode 上引入编译器警告,因此苹果决定将其更改为第一个

关于iPhone - 当 [super init] 失败时使用 self = [super init],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9541972/

相关文章:

ios - 使用 Assets 目录后,iOS7 iPhone 上未显示启动图像

iphone - 使用自定义 View Controller 来管理同一 View 层次结构的不同部分

iphone - 从 iPhone 到 Python/Django 的表情符号

ios - CCCrypt 崩溃(EXC_BAD_ACCESS)

ios - 处理日光时差

iphone - 在 iOS 上将中文 char* 转换为 NSString?

ios - 使用 krpano 创建的 Html 在 iOS 中本地运行的问题

java - 继承类的 ClasscastException

javascript - 使用字符串 "constructor"作为 JavaScript 对象中的键

java - 子类是否可以在不重写的情况下增强父类的方法?