问题描述
据说非原子
选项会让您的 setter方法运行得更快。我用谷歌搜索,但我无法理解。有人可以告诉我为什么吗?
It is said that nonatomic
option will make your setter method run faster. I googled it but am not able to understand. Could someone tell me why?
推荐答案
声明属性 atomic
使编译器成为可能生成阻止并发访问该属性的其他代码。此附加代码锁定信号量,然后获取或设置属性,然后解锁信号量。与设置或获取原始值或指针相比,锁定和解锁信号量是昂贵的(尽管如果考虑应用程序的总体流量,通常可以忽略不计)。
Declaring a property atomic
makes compiler generate additional code that prevents concurrent access to the property. This additional code locks a semaphore, then gets or sets the property, and then unlock the semaphore. Compared to setting or getting a primitive value or a pointer, locking and unlocking a semaphore is expensive (although it is usually negligible if you consider the overall flow of your app).
由于iOS下的大多数类,特别是与UI相关的类,将在单线程环境中使用,因此可以安全地删除 atomic
(即写入 nonatomic
,因为默认情况下属性是 atomic
:即使操作相对便宜,你也不想支付费用你不需要的。
Since most of your classes under iOS, especially the ones related to UI, will be used in a single-threaded environment, it is safe to drop atomic
(i.e. write nonatomic
, because properties are atomic
by default): even though the operation is relatively inexpensive, you do not want to pay for things that you do not need.
这篇关于为什么在Objective C中总是说属性是非原子的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!