It’s funny how often when a person is learning iOS development they simply write atomic or nonatomic for their properties, though having no idea why. I have to laugh because I myself did the same thing.
But what is nonatomic, and what’s atomic? What’s their differences? Here’s a simple explanation.
Atomic and nonatomic have to do with how to handle multithreaded environments. With”atomic”, the synthesized getter and setter methods will always make sure that you receive a whole value. So for example, if you’re running a multithreaded application and the getter method is called by multiple threads (which should rarely ever happen), if the property is set to atomic, a whole value will be returned, but this value can either be the last value before the setter was called, or the value that is being set by the setter, and there’s no way to tell. This is not thread safe because you can’t be sure what value you’re going to receive.
Nonatomic is basically the opposite. Nonatomic doesn’t care whether or not the setter is being called while another thread is trying to get the value of the property, it simply returns whatever it has, whether the return value will be “whole” or not. Nonatomic is considerably faster then atomic.
To illustrate, say you have a box that you’re putting car parts into, and a man inside the box, puts the car parts together, and then hands them back to you outside the box when he’s finished. Now if say this box was atomic, if you put some parts inside the box, but the person inside is not finished putting the parts together, he’ll simply give you back whatever completed part that he has, but it may not be the completed part that you want. However, if this box was nonatomic, he would return to you whatever he already has inside of the box to you, whether he’s finished putting the pieces together or not. This would work perfectly for you though, if you were the only one putting in car parts, because you could put in the car parts and wait until he’s finished, before asking for the completed car part. Make sense?
This is why you mainly use “nonatomic” for your properties, because when you’re only using a single thread, the application will not be able to call the getter and the setter method at the same time, therefore, the compiler must wait until the setter has finished setting the property before it can ever call the getter method.
It is of note though that this only applies if you are @synthesizing the method implementations, that is, having the compiler generate the getter and setter methods for you.
- Always returns a whole value
- Is not thread safe
- Does not always return a whole value
- Is thread safe
- Much faster than atomic
If anyone has anything to add, or if I’ve presented this correctly, feel free to leave a comment.