美文网首页
AssociatedObject关联对象

AssociatedObject关联对象

作者: Nomo_C | 来源:发表于2020-05-20 15:56 被阅读0次

基本用法

以下是几种不同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();
}

相关文章

  • 关联对象 AssociatedObject

    主要包含两个方面内容: 使用关联对象为已经存在的类添加属性 关联对象在底层OC中的实现 @property可以说...

  • AssociatedObject关联对象

    基本用法 以下是几种不同key的写法 关联对象的原理 关联对象不是存储在对象本身的内存中的,它被保存在一个全局的A...

  • iOS 基础知识之关联对象

    简介 associatedObject又称关联对象,把一个对象关联到另外一个对象身上,使两者能够产生联系。关联对象...

  • 关于iOS Class Category的整理

    参考 Category官方指导文档 关联对象 AssociatedObject 完全解析 深入理解Objectiv...

  • 探索AssociatedObject关联对象的内部实现

    AssociatedObject关联对象 为什么要引入关联对象? 一般我们需要对现有的类做扩展,可以通过继承、类别...

  • 【iOS】关联对象详解

    前言 associatedObject又称关联对象。顾名思义,就是把一个对象关联到另外一个对象身上。使两者能够产生...

  • 【iOS】关联对象详解

    前言 associatedObject又称关联对象。顾名思义,就是把一个对象关联到另外一个对象身上。使两者能够产生...

  • 分类-关联对象

    给分类添加成员变量 另一篇:关联对象 AssociatedObject 完全解析.h .m 在其他实例中调用 关联...

  • OC-关联对象AssociatedObject

    关联对象 前言 我们都知道ARC环境下, 在一个类中声明一个属性@property (nonatomic, ass...

  • AssociatedObject关联对象原理实现

    介绍 关联对象(AssociatedObject)是Objective-C 2.0运行时的一个特性,允许开发者对已...

网友评论

      本文标题:AssociatedObject关联对象

      本文链接:https://www.haomeiwen.com/subject/hdcnohtx.html