2

Really quick and simple question: In Objective-C what is the difference between nonatomic and atomic? like when declaring properties like "@property (nonatomic, retain) id object"?

NoodleOfDeath
  • 13,338
  • 21
  • 69
  • 100
  • 1
    Best answer I've seen: http://stackoverflow.com/questions/588866/objective-c-properties-atomic-vs-nonatomic/589392#589392 – Alex Mcp Sep 02 '10 at 03:33

2 Answers2

5

The code for a non atomic retain getter and setter conceptually looks something like:

-(id) foo
{
    return fooIvar;
}

-(void) setFoo: (id) newFoo
{
    [newFoo retain];
    [fooIvar release];
    fooIvar = newFoo; 
}

The code for an atomic getter and setter conceptually looks something like this:

-(id) foo
{
    @synchronized(self)
    {
        return [[fooIvar retain] autorelease];
    }
}

-(void) setFoo: (id) newFoo
{
    @synchronized(self)
    {
        [newFoo retain];
        [fooIvar release];
        fooIvar = newFoo;
    } 
}

The implementation details are different, notably the locking ismore light weight than synchronising the object with the ivar.

In the non atomic case and in a multithreaded environment, you can't guarantee that the getter will give you a valid object because between the getter returning the reference and the caller retaining it (or doing anything else) another thread could call the setter, releasing the object and possibly deallocating it.

In the atomic case, this can't happen because the getter puts the object in the thread's autorelease pool before returning it. If another thread calls the setter and releases the object before the caller has a chance to retain it, it doesn't matter because of the ownership the autorelease pool has.

JeremyP
  • 80,230
  • 15
  • 117
  • 158
  • 1
    I'd like to mention that in the atomic case you have a bit more overhead (as illustrated in the code above), so that's why most people will use nonatomic for declaring a simple pointer. – locoboy Apr 10 '11 at 06:30
  • @cfarm54: To my mind, that would be an example of premature optimisation. I think people should leave properties as atomic (which would be in line with the fact that atomic is the default) unless they can demonstrate a performance issue exists. – JeremyP Apr 11 '11 at 08:50
2

nonatomic - less over head but not thread safe.

AndersK
  • 33,910
  • 6
  • 56
  • 81