iphone - int 的 setter/getter 的正确属性是什么?

标签 iphone objective-c properties getter-setter

我见过许多不同的方法来属性化/合成一个 int,但我不知道正确的方法。

我通常这样做:

@property (nonatomic, assign) int myInt

但我见过人们使用:

@property (nonatomic) int myInt
@property int myInt

哪种方式是正确的?

最佳答案

这里是 a great post about the difference between atomic and nonatomic :

Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory.

With atomic, the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.

In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than atomic.

What atomic does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.

Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.

注意默认是atomic,所以最后一个例子等同于

@property (atomic) int myInt

另一个默认值是assign,因此这两个选项是等价的:

@property (nonatomic, assign) int myInt
@property (nonatomic) int myInt

同样,下面的也是等价的

@property (atomic, assign) int myInt
@property (atomic) int myInt

编辑:正如 Josh 所指出的,包含 atomic 是一个假设的例子。

关于iphone - int 的 setter/getter 的正确属性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6696730/

相关文章:

javascript - Instruments:UI Automation:iPhone app - 如何使用 NSRect 参数点击 "null"按钮?

iphone - 如何使用 CFBundleTypeName 添加 mp3 支持

objective-c - 复制单例实例以存储在数组中

ios - 从 String 到 NSDate 的错误转换

swift - 如果全局属性总是延迟计算,而局部属性从不延迟计算,那么lazy修饰符会修改什么?

objective-c - 如何在 Objective-C 类中设置 boolean 类型属性

iphone - 是否有适用于 iOS 的离线地理编码框架、库或数据库?

ios - 链接错误 Xcode libx264.a ARM

ios - 如何在不丢失选项卡的情况下在选项卡式应用程序上加载另一个 View Controller

php - 从类中变量的函数中获取值