Why properties are always said to be made nonatomic in Objective C? [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

This question already has an answer here:

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?

回答1:

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).

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.



回答2:

see the difference between atomic and nonatomic in objective c

Atomic

Atomic is the default behaviour for a property; by not explicitly setting the above property as nonatomic, it will be atomic.

An atomic property adds a level of thread safety when getting or setting values. That is, the getter and setter for the property will always be fully completed regardless of what other threads are doing. The trade-off is that these properties will be a little slower to access than a nonatomic equivalent.

Non-Atomic

Nonatomic properties are not thread safe, and will return their properties directly. This will be faster than atomic properties, but obviously carries some risk if precautions aren’t made.



回答3:

@property (strong) NSString *str; 

Atomic is the default behaviour for a property; by not explicitly setting the above property as nonatomic, it will be atomic.

setter & getter for these Atomic property

An atomic property adds a level of thread safety when getting or setting values. That is, the getter and setter for the property will always be fully completed regardless of what other threads are doing. these properties will be a little slower to access than a nonatomic equivalent.

@property (strong,nonatomic) NSString *str; 

Nonatomic properties are not thread safe, and will return their properties directly. This will be faster than atomic properties, but obviously carries some risk if precautions aren’t made.

setter & getter for these Nonatomic property

-(NSString *) str{     return str;     }}  -(void) setStr: (NSString *) newString{ str = newString; } 

So by looking on the setter & getter methods for both Atomic & nonatomic that nonatomic methods are very light weight.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!