iOS開發之self.abc = nil與[_abc release]的區別

來源:互聯網
上載者:User

標籤:

前者使用property的點操作符,也就相當於調用了abc對應的set method,和這句是一樣的:[self setAbc:nil];

而後者沒有通過property,直接存取了成員變數,調用了它的release方法。

對於set method來說,用synthesize來讓系統幫我們產生的set方法和如下的類似:

- (void)setAbc:(id)newAbc{      if(_abc != newAbc){           [_abc release];           _abc = [newAbc retain]; //是retain還是copy取決於你property聲明時的attributes         }}

如果新值和成員相等,就不需要進行重複的賦值了,不等的話,需要把新值賦給成員,同時,成員_abc原來的內容就不需要了,這裡要先調用release進行釋放。(這個具體的原因在那本講Objective-C的書中寫的很清楚,請查看)。
因此在這裡,調用self.abc = nil;
就等於掉了[_abc release];  和_abc = nil;

self.abc = nil;和[_abc release]; 都不一定釋放對象,因為該對象還可能被別的引用,這裡的操作的意圖就是:別的地方用沒用_abc我不知道,在這裡的_abc我不用了。

在用retain或者copy的property attributes的時候,self.abc = nil;等於如下語句:
if(_abc!= nil)
{
   [_abc release];
   _abc = nil; //message sent to nil returns nil.
}
所以用起來更簡單一點。

iOS開發之self.abc = nil與[_abc release]的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.