assign,retain和copy

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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 setaccessor. They are mutually exclusive.

strongSpecifies that there is a strong (owning) relationshipto the destination object.

weakSpecifies 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.)

copySpecifies 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.

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

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

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航