2
votes

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"?

2

2 Answers

5
votes

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.

2
votes

nonatomic - less over head but not thread safe.