我见过许多不同的方法来属性化/合成一个 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/