Pages

Monday, October 7, 2013

Atomic vs Nonatomic

In this post I will discuss the difference between (atomic) and (nonatomic).

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.

Nonatomic

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.

When is it Appropriate to Use Nonatomic?

One thing I’ve noticed while following Objective-C tutorials and articles is that nonatomic is used most of the time. So if nonatomic is so risky, why is it used so often?
It’s all about performance. An atomic property’s getter and setter, conceptually, looks something like this:
Whereas a nonatomic property getter and setter looks something like this:
It’s easy to see how the nonatomic implementation is going to be more light weight, but it does mean you have a responsibility to ensure problems don’t arise. Some articles I’ve read recommend keeping things atomic until performance becomes a problem, while others recommend the opposite.
In any event, if you decide to create a nonatomic property, here are some tips for keeping things thread safe:
  • Use immutable objects where possible. For example, rather than creating an NSMutableArray, create an immutable NSArray. Whenever you need to add an object to it, create a mutable copy first and do what you need to do, then replace the entire property in one hit rather than tacking on another value to the end.
  • You can wrap potentially problematic sections of code with @synchronized.
  • UI code can always be nonatomic because UI code always happens on the main thread of the application.