问题描述
作为Objective-C的新手,有人可以根据@property指令向我概述保留,分配,复制以及我缺少的任何其他内容吗?他们在做什么,为什么我要用另一个?
As someone that's new to Objective-C can someone give me an overview of the retain, assign, copy and any others I'm missing, that follow the @property directive? What are they doing and why would I want to use one over another?
推荐答案
由MrMage链接的文章已不再有效。所以,这是我在Objective-C中编写的(非常)短时间内学到的东西:
The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:
非原子与原子
- 原子是默认。始终使用非原子。我不知道为什么,但我读过的那本书说很少有理由使用原子。 (顺便说一下:我读过的书是BNRiOS编程一书。)
nonatomic vs. atomic- "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)
readwrite vs. readonly
- readwrite是默认值。 @synthesize时,将为您创建一个getter和一个setter。如果使用readonly,则不会创建setter。在实例化对象后,将它用于您不希望更改的值。
readwrite vs. readonly- "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.
保留与复制与分配
- assign是默认值。在由@synthesize创建的setter中,该值将简单地分配给该属性。我的理解是assign应该用于非指针属性。
- 当属性是指向对象的指针时,需要retain。由@synthesize生成的setter将保留(也称为保留计数)对象。完成后,您将需要释放该对象。
- 当对象可变时需要复制。如果您此时需要对象的值,请使用此选项,并且您不希望该值反映对象的其他所有者所做的任何更改。完成后,您需要释放该对象,因为您保留了副本。
这篇关于@property在Objective-C中保留,赋值,复制,非原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!