两者之间有什么区别:
// 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/