iPhone SDK Nonatomic and Atomic

2020-04-16 03:50发布

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楼-- · 2020-04-16 03:57

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.

查看更多
▲ chillily
3楼-- · 2020-04-16 04:03

nonatomic - less over head but not thread safe.

查看更多
登录 后发表回答