Should i declare NSLock as atomic, or it's just a waste of time and the lock itself should be non atomic?
Using NSLocks as atomic or non atomic properties?
426 views Asked by Zbun AtThere are 3 answers
On
Think about it. If you have a property that returns an NSLock, will the setter ever be called? Or would that be a horrendous bug that will make your app crash all over the place?
What you should do is have a look at @synchronized and figure out if that might not be a lot, lot easier to use than an NSLock.
On
Should i declare NSLock as atomic, or it's just a waste of time and the lock itself should be non atomic?
By default all properties in Objective-C are atomic. So no need to declare NSLock as atomic. And also it depends on your requirement whether you want to declare as non atomic, basically nonatomic attribute is used for multi threading purposes. If you have set the nonatomic attribute at the time of declaration, then any other thread wanting access to that object can access it and give results in respect to multi-threading.So it is faster as compared to atomic Refer this difference between atomic vs Non atomic
atomic makes setting and getting the property atomic, if the property doesn't need to be accessed atomically, maybe its only reads from multiple threads after if as been set, then it doesn't need to be atomic. Alternatively, how often is this property going to be called, you would need to call it pretty often in a loop to notice the effect of the property being atomic. you can also do things like call the property only once in a method and keep a local reference to it to reduce the overhead of it being atomic.
For properties, if there is any doubt I about whether it needs to be atomic or not, I usually make them atomic, if that creates a performance problem I can look at dealing with that later, but having a bug introduced because of a nonatomic property, is much more serious issue.