iPhone SDK Nonatomic和Atomic [英] iPhone SDK Nonatomic and Atomic

查看:106
本文介绍了iPhone SDK Nonatomic和Atomic的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真正快速而简单的问题:在Objective-C中,非原子和原子有什么区别?比如声明像@property(nonatomic,retain)id object这样的属性?

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

推荐答案

非原子保留吸气剂的代码和setter在概念上看起来像:

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; 
}

原子getter和setter的代码在概念上看起来像这样:

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;
    } 
}

实施细节不同,特别是锁定更轻重量比将对象与ivar同步。

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

在非原子情况下和多线程环境中,你不能保证getter会给你一个有效的对象,因为在返回引用的getter和保留它的调用者(或做其他任何事情)之间,另一个线程可以调用setter,释放对象并可能解除分配它。

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.

在原子中例如,这不可能发生,因为getter在返回之前将对象放入线程的自动释放池中。如果另一个线程调用setter并在调用者有机会保留它之前释放该对象,则由于autorelease池拥有所有权而无关紧要。

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.

这篇关于iPhone SDK Nonatomic和Atomic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆