Objective-C:标量属性默认为原子?
一位朋友告诉我,标量属性(BOOL、NSInteger 等)的 @property 默认值是非原子的。即,
@property BOOL followVenmo;
默认为
@property (nonatomic) BOOL followVenmo;
但是,我总是认为默认值始终是原子的,标量与否。
是哪一个?
A friend told me that the @property default for scalar properties (BOOL, NSInteger, etc.) is nonatomic. I.e.,
@property BOOL followVenmo;
defaults to
@property (nonatomic) BOOL followVenmo;
But, I was always under the impression that the default is always atomic, scalar or not.
Which is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请小心这个“标量”术语。 NSString * 属性也是一个指针,与您提供的带有指向 BOOL 的指针的示例完全相同。
来自 Apple 文档:(Objective-C 编程语言)
您无法在非对象的对象上应用对象级锁,因此基元类型的属性中的(非)原子基本上没有任何效果。
您可以得出结论,原子仅适用于对象属性,并且文档中强化了这一点:
为了澄清是否应该指定其中之一:从技术上讲,没有
非原子
的属性被视为原子,但请记住它对于原始类型没有任何意义。因此,您可能希望节省一些输入并避免在其中使用nonatomic
。Be careful with this "scalar" terminology. An NSString * property is also a pointer, exactly like the example you provided with a pointer to BOOL.
From Apple docs: (The Objective-C Programming Language)
You can't apply an object-level lock in something that's not an object, so (non)atomic in properties of primitive types has basically no effect.
You can conclude that atomic only applies to object properties, and this is reinforced in the docs:
To clarify whether you should specify one or the other: technically, properties without a
nonatomic
are considered atomic, but remember that it has no meaning for primitive types. Thus, you may want to save some typing and avoidnonatomic
in these.基于我对其他几个相关问题的研究:
我将遵守@Rhubarb 的建议:
Based on my research of a couple other related questions:
I shall abide by @Rhubarb's recommendation:
来自 开发者文档
原子属性确保您将获取或设置整个值。例如,从 2 个线程设置 CGRect 最终会得到其中一个,而不是两者的某种组合。
对于保留的属性,它还确保结果可以比接收者更长久。例如,您从另一个线程在调用完成之前释放的对象中获取结果,但该结果会代表您保留并自动释放,因此它仍然有效。
From the Developer Documentation
Atomic properties ensures that you will get or set a whole value. For example, setting a CGRect from 2 threads will end up with one or the other, not some combination of the two.
For retained properties, it also ensures that the result can outlive the receiver. For example, you get a result from an object that is released by another thread before the call finishes, but the result is retained and autoreleased on your behalf so it is still valid.