![](/img/trans.png)
[英]if (self = [super init]) vs. if ((self = [super init]))
[英]iPhone - Use of self = [super init] when [super init] fails
有什么區別:
// 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上引入編譯器警告,因此蘋果決定將其改為第一個
==
而不是=
。 您可以通過在表達式周圍使用另一個(...)
來阻止警告,但這並不容易閱讀。 nil
使代碼更容易理解(也許這只是我的意見,其他人可以說4比3更好)。 總結:使用1或3.當初始化代碼很長時,你應該使用3來避免在一個if
塊中使用大多數方法代碼。 Apple僅使用1但不盲目追隨。 Apple沒有記錄編碼標准,有時他們推薦的是非常值得懷疑的。
您可以使用4而不是3,但不要在代碼中混用3和4。
建議1只是因為它很清楚。
2作品,但只是不好的做法。 如果你不需要,不要在你的條件中嵌入邏輯。
3讓我頭疼。 通常,如果可以,您希望避免否定檢查。
4與3相同。
1和2都比3和4更容易閱讀,也因為它們是Apple代碼中使用的那個; 許多開發人員習慣於1和2。
數字4和3是相同的,好像!self
評估為true,那么它意味着self
是nil
,所以語句return self
是equivelant return nil
。 有些人會說你不應該在方法中有多個退出點(返回),但實際上有多個return語句可以減少if語句的數量(這會降低可讀性)
數字2已經很常見了,但是在xcode的最新版本中,你會得到一個編譯器警告if和if
語句是否包含單個=
(當你打算使用==
來比較BOOL
值時,這是很多次它是一個錯字)。 為了使這個警告保持沉默,你必須用括號括起語句,所以不是if (foo = bar)
而是if ((foo = bar))
但Apple必須意識到Number 2已被大量使用,並且他們在規則中添加了一個例外,所以你使用它現在不會引起編譯器警告。
由於Number 2是規則的例外,因此您不應該使用它。 這使得Number 1成為首選方法。
加入戰斗..我更喜歡:
if(!(self = [super init]) ) return self;
將所有內容保留在一行上,並且在XCode 4.2中沒有警告:D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.