What's the difference between 'atomic' and non-atomic? [duplicate]
Possible Duplicate:
Atomic vs nonatomic properties
I just want to know what is the differneve between theses two lines of code :
@property(nonatomic, retain) NSString *str;
and
@property(atomic, retain) NSString *str;
Thanx, Regards, tek3
Atomic properties are necessary in a reference counted multi threaded environment in order to stop objects from disappearing before a thread has a chance to retain them.
Consider the naive implementation of a get accessor:
@interface MyObject : NSObject
{
id myPropertyIVar;
}
-(id) myProperty;
@end
@implementation MyObject
-(id) myProperty
{
return myPropertyIvar;
}
// other stuff
@end
This is all fine except that if you release the instance of MyObject before retaining the returned value from -myProperty the returned value may well be deallocated. For this reason, it is safer to implement -myProperty like this:
-(id) myProperty
{
return [[myPropertyIvar retain] autorelease];
}
This is now completely safe in a single threaded environment.
Unfortunately, in a multithreaded environment there is a race condition. If the thread is interrupted at any time before the retain has incremented the retain count, either of the following will cause you to receive a garbage pointer:
- the instance of MyObject is released and deallocated by another thread causing the ivar to be released and deallocated
- myProperty is reassigned by another thread causing the old version to be released and deallocated
For this reason, all accesses to the property must be protected by a lock. The get accessor looks something like this.
-(id) myProperty
{
// lock
return [[myPropertyIvar retain] autorelease];
// unlock
}
The set accessor is similarly protected and so is the release in -dealloc
The Apple docs explain all this very well. To learn about properties, including their atomicity, read this page.
精彩评论