OBJC_ASSOCIATION_ASSIGN是指原子还是非原子?

时间:2014-03-02 02:28:44

标签: objective-c objective-c-runtime

OBJC_ASSOCIATION_ASSIGNobjc_setAssociatedObject的第四个参数,是指原子还是非原子?

此枚举定义为

enum {
    OBJC_ASSOCIATION_ASSIGN = 0,
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
    OBJC_ASSOCIATION_RETAIN = 01401,
    OBJC_ASSOCIATION_COPY = 01403
};

什么是@property(assign, atomic) id idAssignAtomic;

什么是@property(assign, nonatomic) id idAssignNonatomic;

1 个答案:

答案 0 :(得分:1)

目前(从iOS 8和OS X 10.10开始),内部所有关联都是原子化的。如果我们查看objc-references.mm的来源:

,就可以看到这一点
// class AssociationsManager manages a lock / hash table singleton pair.
// Allocating an instance acquires the lock, and calling its assocations() method
// lazily allocates it.

class AssociationsManager {
    static spinlock_t _lock;
    static AssociationsHashMap *_map;               // associative references:  object pointer -> PtrPtrHashMap.
public:
    AssociationsManager()   { spinlock_lock(&_lock); }
    ~AssociationsManager()  { spinlock_unlock(&_lock); }

    AssociationsHashMap &associations() {
        if (_map == NULL)
            _map = new AssociationsHashMap();
        return *_map;
    }
};

具体来说,请注意_lock_map都是静态的,并按此定义:

spinlock_t AssociationsManager::_lock = SPINLOCK_INITIALIZER;
AssociationsHashMap *AssociationsManager::_map = NULL;

然后,当两者都获得关联并释放它时,我们会看到以下内容:

AssociationsManager manager;
AssociationsHashMap &associations(manager.associations());

这清楚地表明每个关联都是原子的,并且独立于在此过程中存储或检索的所有其他关联。

但请记住,与运行时中的任何内容一样,这些内容在将来的版本中都会发生变化,除了学术目的之外,您不应该依赖此行为。