8

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

Community
  • 1
  • 1
tek3
  • 2,035
  • 2
  • 20
  • 50

2 Answers2

8

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

JeremyP
  • 80,230
  • 15
  • 117
  • 158
  • Thanx a lot JeremyP. I really gleaned a lot from your answer. – tek3 Jul 26 '10 at 11:39
  • Not quite the full story. :) An atomic property does not actually guarantee thread safety. It only guarantees that you'll get/set an integral value. – bbum Jul 26 '10 at 15:50
  • @bbum: Ha, I knew I should have put that bit in too. In my defence, you'll notice that I haven't even claimed atomic properties guarantee thread safety, only that it makes it *possible* to get a property safely in a multithreaded environment. – JeremyP Jul 27 '10 at 07:45
2

The Apple docs explain all this very well. To learn about properties, including their atomicity, read this page.

mk12
  • 24,644
  • 29
  • 92
  • 132