What do atomic and nonatomic mean in property declarations?
@property(nonatomic, retain) UITextField *userName;
@property(atomic, retain) UITextField *userName;
@property(retain) UITextField *userName;
What is the operational difference between these three?
Answer
Atomic
- is the default behavior
- will ensure the present process is completed by the CPU, before another process accesses the variable
- is not fast, as it ensures the process is completed entirely
- thread safe
- ues if the instance variable is gonna be accessed in a multithreaded environment.
Non-Atomic
- is NOT the default behavior
- faster (for synthesized code, that is, for variables created using @property and @synthesize)
- not thread-safe
- may result in unexpected behavior, when two different process access the same variable at the same time
- use if the instance variable is not gonna be changed by multiple threads you can use it. It improves the performance.
Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operations on different threads will be performed serially which means if one thread is executing a setter or getter, then other threads will wait.
If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, either one of A, B or C will execute first, but D can still execute in parallel.