iPhone - 当[super init]失败时使用self = [super init] [英] iPhone - Use of self = [super init] when [super init] fails
本文介绍了iPhone - 当[super init]失败时使用self = [super init]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么区别:
// 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。
EDIT : Added thanks to 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;
}
推荐答案
- Apple使用的常用文件
- 是否相同,但编译器不知道你是不是指
==
而不是=
。您可以通过在表达式周围使用另一个(...)
来阻止警告,但这并不容易阅读。 - 这个任何好的编码标准都会优先考虑(通常不是单线,而是带有护腕)。当您的初始化代码很长时,这会显着提高可读性。
- 与3相同,但您失去了一些可读性。返回
nil
使代码更容易理解(也许这只是我的意见,其他人可以说4优于3)。
- The common one used by Apple
- Does the same but the compiler does not know if you didn't mean
==
instead of=
. You can block the warning by using another(...)
around the expression, but it's not easy to read. - This one would be preferred by any good coding standards (usually not as a one-liner but with bracers). When your initialization code is long, this one significantly increase readibility.
- The same as 3 but you lose some readibility. Returning
nil
makes the code easier to understand (maybe this is only my opinion, someone else can say 4 is better than 3).
总结:使用1或3.当初始化代码很长时,你应该使用3来避免大多数方法代码在一个中,如果
阻止。 Apple仅使用1但不盲目跟随它。 Apple没有记录编码标准,有时他们推荐的内容非常值得怀疑。
In summary: use 1 or 3. When initialization code is long, you should use 3 to avoid having most of method code in one if
block. Apple uses only 1 but don't follow it blindly. Apple has no documented coding standards and sometimes what they recommend is very questionable.
你可以用4而不是3但不要混用3&你的代码中有4个。
You can use 4 instead of 3 but don't mix 3 & 4 in your code.
这篇关于iPhone - 当[super init]失败时使用self = [super init]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文