...let John help you code



What's the difference between the atomic and nonatomic attributes?

Asked by:
mod5
Nov 13, 2016, 22:42

Description

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?

1 Answer

Answer :
Code

Preview
 

4

This is explained in Apple's documentation, but below are some examples of what is actually happening. Note that there is no "atomic" keyword, if you do not specify "nonatomic" then the property is atomic, but specifying "atomic" explicitly will result in an error.
//@property(nonatomic, retain) UITextField *userName;
//Generates roughly

- (UITextField *) userName {
return userName;
}

- (void) setUserName:(UITextField *)userName_ {
[userName_ retain];
[userName release];
userName = userName_;
}


Now, the atomic variant is a bit more complicated:
 //@property(retain) UITextField *userName;
//Generates roughly

- (UITextField *) userName {
UITextField *retval = nil;
@synchronized(self) {
retval = [[userName retain] autorelease];
}
return retval;
}

- (void) setUserName:(UITextField *)userName_ {
@synchronized(self) {
[userName release];
userName = [userName_ retain];
}
}


Basically, the atomic version has to take a lock in order to guarantee thread safety, and also is bumping the ref count on the object (and the autorelease count to balance it) so that the object is guaranteed to exist for the caller, otherwise there is a potential race condition if another thread is setting the value, causing the ref count to drop to 0.

There are actually a large number of different variants of how these things work depending on whether the properties are scalar values or objects, and how retain, copy, readonly, nonatomic, etc interact. In general the property synthesizers just know how to do the "right thing" for all combinations.
Frank-en-teins