首页 > 代码库 > 【整理】Object-C中的属性(Property)的Setter:assign,copy,retain,weak,strong之间的区别和联系

【整理】Object-C中的属性(Property)的Setter:assign,copy,retain,weak,strong之间的区别和联系

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,不会释放旧的对象;

【整理】Object-C中的属性(Property)的Setter:assign,copy,retain,weak,strong之间的区别和联系