【整理】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 SemanticsThese 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,不會釋放舊的對象;