Friday, September 28, 2012

@property(nonatomic, retain) ?

@property(nonatomic, retain) ?

By default, property accessors are atomic. Also 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.

So if any one write

@property(atomic, retain) UITextField *userName;
@property(retain) UITextField *userName;

They mean the same thing.

So an Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.

With atomic, the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.

In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than atomic.

What atomic does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.

No comments:

Post a Comment