美文网首页
Category关联对象探究

Category关联对象探究

作者: 飞奔的小鲨鱼 | 来源:发表于2018-12-18 14:37 被阅读0次

在日常开发的过程中经常会用到在category中添加属性的需求,在添加属性后是默认不会自动生成setter和getter方法的,需要我们自己手动添加,这就用到了runtime的两个方法,objc_setAssociatedObjectobjc_getAssociatedObject

@interface Person (category1)
@property (nonatomic, copy) NSString * address;
@end
static const NSString * associate_address = @"address";
@implementation Person (category1)
- (void)setAddress:(NSString *)address{
    objc_setAssociatedObject(self, 
                             &associate_address,
                             address, 
                             OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)address{
    return objc_getAssociatedObject(self, &associate_address);
}

@end

这个分类的关联对象到底是这么实现的,我们在objc-runtime.mm文件中或许会找到答案

id objc_getAssociatedObject(id object, const void *key) {
    return _object_get_associative_reference(object, (void *)key);
}

void objc_setAssociatedObject(id object, 
                              const void *key, 
                              id value, 
                              objc_AssociationPolicy policy) {
    _object_set_associative_reference(object, (void *)key, value, policy);
}


void objc_removeAssociatedObjects(id object) 
{
    if (object && object->hasAssociatedObjects()) {
        _object_remove_assocations(object);
    }
}

objc_setAssociatedObject

void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {
    // retain the new value (if any) outside the lock.
    ObjcAssociation old_association(0, nil);
   // 通过acquireValue方法对传入的value进行retain或者copy,得到新的new_value
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        // 创建manager,manager里面有一个AssociationsHashMap类型的哈希表
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        // 将object简单处理成~uintptr_t(value)类型
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // break any existing association.
            // 通过disguised_object找到对应的AssociationsHashMap
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i != associations.end()) {
                // secondary table exists
                // i->first disguised_object ,i->second ObjectAssociationMap
                ObjectAssociationMap *refs = i->second;
                //   通过key找到对应的ObjectAssociationMap
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    // 如果对应的ObjectAssociationMap存在,取出旧值释放,更新新值
                    // j->first 绑定关联对象传入的key
                    // j->second ObjcAssociation(policy, new_value)
                    old_association = j->second;
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    // 如果不存在,以key-ObjcAssociation键值对的形式存入表中
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                }
            } else {
                // create the new association (first time).
                // 如果disguised_object对应的哈希表不存在
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                // 将disguised_object作为 key ,refs(ObjectAssociationMap)作为value
                // 存入AssociationsHashMap表中
                associations[disguised_object] = refs;
                // 将传入的key 为key,ObjcAssociation为value存入表中
                (*refs)[key] = ObjcAssociation(policy, new_value);
                // 设置当前对象绑定关联对象
                object->setHasAssociatedObjects();
            }
        } else {
            // setting the association to nil breaks the association.
            // 如果设置的value 为nil,找到对应的key删除
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i !=  associations.end()) {
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    refs->erase(j);
                }
            }
        }
    }
    // release the old value (outside of the lock).
   // 释放 old_association
    if (old_association.hasValue()) ReleaseValue()(old_association);
}

用下面的一张图来说明AssociationsManagerAssociationsHashMap,ObjectAssociationMap,ObjectAssociations它们之间的关系:

set_associative.png

至此,通过上图可以看出它们之间的关系:
关联对象并没有添加在原来的类或者分类上,而是放在了一张哈希表中,将传入的object转化为disguised_object作为key,ObjectAssociationMap作为value放在了AssociationsHashMap表中,而ObjectAssociationMap表中存放的是以传入的key作为key,ObjcAssociation作为value的数据关系,ObjcAssociation中保存的是传入的value和policy。

那我们接下来看看它是这么取值的吧

objc_getAssociatedObject

id _object_get_associative_reference(id object, void *key) {
    id value = nil;
    uintptr_t policy = OBJC_ASSOCIATION_ASSIGN;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object);
        AssociationsHashMap::iterator i = associations.find(disguised_object);
        if (i != associations.end()) {
            ObjectAssociationMap *refs = i->second;
            ObjectAssociationMap::iterator j = refs->find(key);
            if (j != refs->end()) {
                ObjcAssociation &entry = j->second;
                value = entry.value();
                policy = entry.policy();
                if (policy & OBJC_ASSOCIATION_GETTER_RETAIN) {
                    objc_retain(value);
                }
            }
        }
    }
    if (value && (policy & OBJC_ASSOCIATION_GETTER_AUTORELEASE)) {
        objc_autorelease(value);
    }
    return value;
}

取值看起来就比较简单了,通过disguised_objectkey找到对应ObjcAssociation,返回里面保存的value。这也就是为什么在取值的时候只需要传入object和key,就可以取到值了。

objc_removeAssociatedObjects

void _object_remove_assocations(id object) {
    vector< ObjcAssociation,ObjcAllocator<ObjcAssociation> > elements;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        if (associations.size() == 0) return;
        disguised_ptr_t disguised_object = DISGUISE(object);
        // 
        AssociationsHashMap::iterator i = associations.find(disguised_object);
        if (i != associations.end()) {
            // copy all of the associations that need to be removed.
            ObjectAssociationMap *refs = i->second;
            for (ObjectAssociationMap::iterator j = refs->begin(), end = refs->end(); j != end; ++j) {
                elements.push_back(j->second);
            }
            // remove the secondary table.
            delete refs;
            associations.erase(i);
        }
    }
    // the calls to releaseValue() happen outside of the lock.
    for_each(elements.begin(), elements.end(), ReleaseValue());
}

上述源码可以看出_object_remove_assocations函数将object对象所有关联对象全部删除。

相关文章

  • Category关联对象探究

    在日常开发的过程中经常会用到在category中添加属性的需求,在添加属性后是默认不会自动生成setter和get...

  • Category关联对象

    一、分类中添加成员变量Category中添加成员变量.png 所以Category中是不能添加成员变量 二、Cat...

  • Category关联对象

    OC中的分类严格来说,是不能添加对象;但是我们可以通过OC运行是的机制,动态为分类添加属性 一、类中的属性 当在类...

  • 关联对象

    关联对象 关联对象一般用来配合 Category 使用,在 Category 中声明属性时编译器只会自动生成 Ge...

  • iOS关联对象的源码探究

    本文探究问题:- 怎么通过关联对象为分类category添加成员变量?- 添加的成员变量被存储在哪了? 1.为分类...

  • 关于分类(Category)关联对象的一些了解

    本文是关于Category关联对象的一些理解化,以及部分使用建议。仅适用于新手玩家(对Category关联对象停留...

  • Category使用关联对象生成属性的原理

    Category关联对象: main.m文件: NSString+Category.h文件: NSString+C...

  • Objective-C--关联对象(AssociateObjec

    关联对象的用途 在Category中为已经注册的类增加存储字段,模拟实例变量。 关联对象存储原理 所有的关联对象都...

  • Category-关联对象

    分类添加属性 Category能否添加成员变量?如果可以,如何给Category添加成员变量?不能直接给Categ...

  • Category &associate 关联对象

    手动为Category生成一个成员变量 默认情况下,因为分类底层架构的限制,不能添加到成员变量到分类中,但是可以通...

网友评论

      本文标题:Category关联对象探究

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