【整理】Object-C中的屬性(Property)的Setter:assign,copy,retain,weak,strong之間的區別和聯絡,object-csetter

來源:互聯網
上載者:User

【整理】Object-C中的屬性(Property)的Setter:assign,copy,retain,weak,strong之間的區別和聯絡,object-csetter
iOS編程過程中,經常看到一些屬性前面有些修飾符,比如copy,retain等。

這些關鍵字,是Object-C語言中,對於Property的setter。

Mac官網:

The Objective-C Programming Language – Declared Properties – Setter Semantics

中的解釋是:

Setter Semantics

These attributes specify the semantics of a set accessor. They are mutually exclusive.

strong

Specifies that there is a strong (owning) relationship to the destination object.

weak

Specifies that there is a weak (non-owning) relationship to the destination object.

If the destination object is deallocated, the property value is automatically set to nil.

(Weak properties are not supported on OS X v10.6 and iOS 4; use assigninstead.)

copy

Specifies that a copy of the object should be used for assignment.

The previous value is sent a release message.

The copy is made by invoking the copy method. This attribute is valid only for object types, which must implement the NSCopying protocol.

assign

Specifies that the setter uses simple assignment. This attribute is the default.

You use this attribute for scalar types such as NSInteger and CGRect.

retain

Specifies that retain should be invoked on the object upon assignment.

The previous value is sent a release message.

In OS X v10.6 and later, you can use the __attribute__ keyword to specify that a Core Foundation property should be treated like an Objective-C object for memory management:

@property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary;

即使看完解釋,其實也很難理解具體的含義。

 

後來是看了很多人的總結,,再經過一些實際編程的折騰,尤其是:

【已解決】iOS程式出現警告:ARC Semantic Issue,Assigning retained object to unsafe property;object will be released after assignment,之後程式運行出錯:Thread 1: EXC_BAD_ACCESS(code=1,address=0xe0000010)

才稍微有所理解的。

 

整理如下:

想要理解這幾個setter的含義,必須先對Object-C中的ARC有所瞭解。

關於ARC,簡單說幾句就是,編譯器自動幫你實現了引用技術,不用再麻煩你去寫retain,release等詞去操心引用技術的事情了。

關於ARC更詳細的解釋,可參考:

【總結】iOS的自動引用計數(ARC,Automatic Reference Counting)

 

strong和weak

自從有了ARC,就可以使用weak或strong來說明屬性是弱引用還是強引用;

 

assign,retain和copy

沒有ARC之前,都是使用assign,retain,copy來修飾屬性的。

assign,主要用於數值類變數,即標量,直接賦值即可,不涉及引用計數的變化(標量值,也沒有引用技術可以供管理);

copy,是拷貝一份新的對象,引用計數重設為1,釋放舊的對象;

retain,是對於原對象,引用計數加1,不會釋放舊的對象;

聯繫我們

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