【整理】Object-C中的属性(Property)的Setter:assign,copy,retain,weak,strong之间的区别和联系
这些关键字,是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
assign
instead.)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 theNSCopying
protocol.assign
Specifies that the setter uses simple assignment. This attribute is the default.
You use this attribute for scalar types such as
NSInteger
andCGRect
.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
@property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary;__attribute__
keyword to specify that a Core Foundation property should be treated like an Objective-C object for memory management:
即使看完解释,其实也很难理解具体的含义。
后来是看了很多人的总结,,再经过一些实际编程的折腾,尤其是:
才稍微有所理解的。
整理如下:
想要理解这几个setter的含义,必须先对Object-C中的ARC有所了解。
关于ARC,简单说几句就是,编译器自动帮你实现了引用技术,不用再麻烦你去写retain,release等词去操心引用技术的事情了。
关于ARC更详细的解释,可参考:
strong和weak
自从有了ARC,就可以使用weak或strong来说明属性是弱引用还是强引用;
assign,retain和copy
没有ARC之前,都是使用assign,retain,copy来修饰属性的。
assign,主要用于数值类变量,即标量,直接赋值即可,不涉及引用计数的变化(标量值,也没有引用技术可以供管理);
copy,是拷贝一份新的对象,引用计数重置为1,释放旧的对象;
retain,是对于原对象,引用计数加1,不会释放旧的对象;