Objective-C声明的@property属性(非原子,复制,强,弱) [英] Objective-C declared @property attributes (nonatomic, copy, strong, weak)
问题描述
当我必须使用每个属性(nonatomic
,copy
,strong
,weak
等)时,有人可以向我详细解释一个声明的属性,并解释每个属性做什么?某种例子也很好.我正在使用ARC.
Can someone explain to me in detail when I must use each attribute: nonatomic
, copy
, strong
, weak
, and so on, for a declared property, and explain what each does? Some sort of example would be great also. I am using ARC.
推荐答案
此答案有很多错误,并且已经过时.请查看其他问题/答案和评论.
非原子
nonatomic
用于多线程目的.如果我们在声明时设置了非原子属性,那么任何其他想要访问该对象的线程都可以访问它,并给出有关多线程的结果.
nonatomic
is used for multi threading purposes. If we have set the nonatomic attribute at the time of declaration, then any other thread wanting access to that object can access it and give results in respect to multi-threading.
复制
copy
.如果您现在需要该对象的值,并且不希望该值反映该对象的其他所有者所做的任何更改,请使用此值.完成操作后,您将需要释放该对象,因为您将保留该副本.
copy
is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.
分配
Assign
与copy
有点相反.调用assign
属性的getter时,它将返回对实际数据的引用.通常,当您具有基本类型的属性(float,int,BOOL ...)时,可以使用此属性
Assign
is somewhat the opposite to copy
. When calling the getter of an assign
property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)
保留
retain
. @synthesize
生成的设置器将保留(也向其添加保留计数)对象.完成处理后,您将需要释放该对象.通过使用保留,它将增加保留计数并占用自动释放池中的内存.
retain
is required when the attribute is a pointer to an object. The setter generated by @synthesize
will retain (aka add a retain count to) the object. You will need to release the object when you are finished with it. By using retain it will increase the retain count and occupy memory in autorelease pool.
强
strong
替代了keep属性,这是Objective-C自动参考计数(ARC)的一部分.在非ARC代码中,它只是保留的同义词.
strong
is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.
这是一个学习iOS 5的strong
和weak
的好网站.
http://www.raywenderlich.com/5677/beginning -arc-in-ios-5-part-1
This is a good website to learn about strong
and weak
for iOS 5.
http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
弱
weak
与strong
相似,不同之处在于它不会将引用计数增加1.它不会成为该对象的所有者,而仅持有对该对象的引用.如果该对象的引用计数降至0,即使您可能仍在此处指向它,它也会从内存中释放.
weak
is similar to strong
except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.
上面的链接同时包含有关弱和强"的良好信息.
The above link contain both Good information regarding Weak and Strong.
这篇关于Objective-C声明的@property属性(非原子,复制,强,弱)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!