[英]Difference between the use of withObject:self and withObject:nil
[英]What's the difference between self.foo=nil and [self setFoo:nil]?
在xcode中,在創建UIViewController子類之后,在viewDidUnload方法中,xcode添加了注釋:
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
在這里,xcode建議我們使用self.myOutlet = nil釋放對象。
但是在xcode4中,有一個很酷的功能:您可以將Interface Builder出口拖到其所有者的頭文件中,然后xcode將在viewDidUnload方法中自動創建IBOutlet對象和相關的發布代碼。
問題是在上述情況下,它生成的代碼是這樣的:
- (void)viewDidUnload {
[super viewDidUnload];
[self setFoo:nil];
}
我提到“ self.foo = nil;” 替換為“ [self setFoo:nil];”。
有人知道區別嗎? 如果沒有區別,為什么xcode4會更改它?
謝謝。
在可執行文件中,兩種語法之間沒有區別。 我能想到的Xcode明確使用setter方法的唯一技術原因是為了與不支持點語法的Objective-C 2.0以前的代碼兼容。 我不知道為什么Xcode需要支持這種兼容性。 可能Xcode生成set-to-nil表達式的部分早於Objective-C 2.0。
也許編寫Xcode的那部分人根本不喜歡點語法。 當首次引入點語法時,很多人不喜歡它。
http://weblog.bignerdranch.com/?p=83
http://www.cimgf.com/2008/07/08/a-case-against-dot-syntax/
http://cocoawithlove.com/2008/08/in-defense-of-objective-c-20-properties.html
這兩個調用都將執行相同的操作。
self.foo = nil;
是以下內容的點語法版本:
[self setFoo:nil];
沒有性能差異,只是您喜歡如何編寫代碼的偏好問題。
我認為self.foo
可以是一個setter/getter
取決於使用情況),而[self setFoo]
是對setter
的顯式調用。
在正常使用中,兩者應相同。
目標C中的點符號博客條目 http://weblog.bignerdranch.com/?p=83
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.