AssociatedObject关联对象

基本用法

以下是几种不同key的写法

static void *SetAgeKey = &SetAgeKey;
- (void)setAge:(NSInteger)age{
    objc_setAssociatedObject(self, SetAgeKey, @(age), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)age{
    return [objc_getAssociatedObject(self, SetAgeKey) integerValue];
}
static char SetAgeKey;
- (void)setAge:(NSInteger)age{
    objc_setAssociatedObject(self, &SetAgeKey, @(age), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)age{
    return [objc_getAssociatedObject(self, &SetAgeKey) integerValue];
}
- (void)setAge:(NSInteger)age{
    objc_setAssociatedObject(self, @"SetAgeKey", @(age), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)age{
    return [objc_getAssociatedObject(self, @"SetAgeKey") integerValue];
}
- (void)setAge:(NSInteger)age{
    objc_setAssociatedObject(self, @selector(age), @(age), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)age{
    return [objc_getAssociatedObject(self, @selector(age)) integerValue];
}

关联对象的原理

关联对象不是存储在对象本身的内存中的,它被保存在一个全局的AssociationsManager

相关的类
AssociationsManager
AssociationsHashMap
ObjectAssociationMap
ObjcAssociation

以下面set方法为例,说明相关类的作用

- (void)setAge:(NSInteger)age{
    objc_setAssociatedObject(self, SetAgeKey, @(age), OBJC_ASSOCIATION_ASSIGN);
}

ObjcAssociation中保存了 @(age)OBJC_ASSOCIATION_ASSIGN
ObjectAssociationMap是一个哈希表,SetAgeKeyObjcAssociation以key、value的形式保存在其中
AssociationsHashMap也是一个哈希表,selfObjectAssociationMap以key、value的形式保存在其中
AssociationsManager全局同一个一个实例,其中包含AssociationsHashMap

示意图

源码分析

源码版本objc4-781.tar.gz

入口:objc-references.mm
void _object_set_associative_reference(id object, const void *key, id value, uintptr_t policy)
id _object_get_associative_reference(id object, const void *key)

设置关联对象

void
_object_set_associative_reference(id object, const void *key, id value, uintptr_t policy)
{
    // This code used to work when nil was passed for object and key. Some code
    // probably relies on that to not crash. Check and handle it explicitly.
    // rdar://problem/44094390
    if (!object && !value) return;

    if (object->getIsa()->forbidsAssociatedObjects())
        _objc_fatal("objc_setAssociatedObject called on instance (%p) of class %s which does not allow associated objects", object, object_getClassName(object));

    // 在AssociationsHashMap中的key
    DisguisedPtr<objc_object> disguised{(objc_object *)object};
    // 包装值和内存策略
    ObjcAssociation association{policy, value};

    // retain the new value (if any) outside the lock.
    association.acquireValue();

    {
        AssociationsManager manager;
        // AssociationsHashMap
        // key:使用关联对象生成的disguised作为key
        // value也是hashmap(ObjectAssociationMap)
        // ObjectAssociationMap
        // key:就是关联对象设置时的key
        // value:association,保存了关联对象的值和内存策略
        AssociationsHashMap &associations(manager.get());
        
        if (value) {
            // 如果不存在以disguised为key的ObjectAssociationMap,则插入key,value
            auto refs_result = associations.try_emplace(disguised, ObjectAssociationMap{});
            if (refs_result.second) {
                // refs_result.second为true表示原来不存在,拆入了新的key、value
                /* it's the first association we make */
                object->setHasAssociatedObjects();
            }

            /* establish or replace the association */
            auto &refs = refs_result.first->second;
             // 如果不存在key、association,则插入key,value
            auto result = refs.try_emplace(key, std::move(association));
            if (!result.second) {
                // result.second false表示,存在旧的值
                // 更新旧的值
                association.swap(result.first->second);
            }
        } else {
            // value为nil,删除原来的值
            auto refs_it = associations.find(disguised);
            if (refs_it != associations.end()) {
                // 存在ObjectAssociationMap
                auto &refs = refs_it->second;
                auto it = refs.find(key);
                if (it != refs.end()) {
                    // ObjectAssociationMap中,存在旧的值
                    association.swap(it->second);
                    // 删除值
                    refs.erase(it);
                    if (refs.size() == 0) {
                        // ObjectAssociationMap中为空,从AssociationsHashMap中删除
                        associations.erase(refs_it);

                    }
                }
            }
        }
    }

    // release the old value (outside of the lock).
    association.releaseHeldValue();
}

读取关联对象

id
_object_get_associative_reference(id object, const void *key)
{
    ObjcAssociation association{};

    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.get());
        AssociationsHashMap::iterator i = associations.find((objc_object *)object);
        if (i != associations.end()) {
            ObjectAssociationMap &refs = i->second;
            ObjectAssociationMap::iterator j = refs.find(key);
            if (j != refs.end()) {
                association = j->second;
                association.retainReturnedValue();
            }
        }
    }

    return association.autoreleaseReturnedValue();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。