iOS中self.xxx 和 _xxx 底線的區別

來源:互聯網
上載者:User

標籤:

property (nonatomic,copy) NSString *propertyName; self.propertyName 是對屬性的拜訪; _propertyName 是對部分變數的拜訪。 其1、@property的聲明中,編譯器正在天生g] 


@property (nonatomic,copy) NSString *propertyName;

self.propertyName 是對屬性的訪問;

_propertyName 是對局部變數的訪問。

其一、@property的聲明中,編譯器在產生getter,setter方法時是有優先順序的,它首先尋找當前的類中使用者是否已定義屬性的getter,setter方法,如果有,則編譯器會跳過,不會再產生,使用使用者定義的方法。 

也就是說你在使用self.propertyName 時是在調用一個getter方法。

self.propertyName 會讓計數器+1;

其二、_propertyName,是直接調用變數,不通過getter方法。  

_propertyName是類似於self->_propertyName。

用self.propertyName 是更好的選擇,因為這樣可以相容懶載入,同時也避免了使用底線的時候忽視了self這個指標,後者容易在block中造成循環參考。

同時,使用 _是擷取不到父類的屬性,因為它只是對局部變數的訪問。

最後總結:self方法實際上是用了get和set方法間接調用,底線方法是直接對變數操作。

iOS中self.xxx 和 _xxx 底線的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.