RunTime源码阅读(二)关联对象

2020-01-17  本文已影响0人  某非著名程序员

1. 三个方法

objc_setAssociatedObject
objc_getAssociatedObject
objc_removeAssociatedObjects

2原理

2.1objc_setAssociatedObject

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

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);
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // break any existing association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            //同一个对象只会创建一个ObjectAssociationMap对象。?
            if (i != associations.end()) {
                // secondary table exists
                //当前对象已经创建关联对象时
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    (*refs)[key] = ObjcAssociation(policy, new_value);//对象置nil后再关联对象
                }
            } else {
                // create the new association (first time).
                //当前对象没有创建关联对象时
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                associations[disguised_object] = refs;
                (*refs)[key] = ObjcAssociation(policy, new_value);
                object->setHasAssociatedObjects();
            }
        } else {
            // setting the association to nil breaks the association.
            // 当前对象value设置为nil时,释放ObjectAssociationMap对象
            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).
    if (old_association.hasValue()) ReleaseValue()(old_association);
}

static id acquireValue(id value, uintptr_t policy) {
    switch (policy & 0xFF) {
    case OBJC_ASSOCIATION_SETTER_RETAIN:
        return objc_retain(value);
    case OBJC_ASSOCIATION_SETTER_COPY:
        return ((id(*)(id, SEL))objc_msgSend)(value, SEL_copy);
    }
    return value;
}
  1. 全局维护AssociationsManager,管理类中存放的是AssociationsHashMap。
  2. acquireValue如果是OBJC_ASSOCIATION_SETTER_RETAIN或OBJC_ASSOCIATION_SETTER_COPY,对value进行retain和copy操作。与引用计数管理相同。
  3. 存储时,通过DISGUISE(object)作为key查找,associations没有存储时会走else
ObjectAssociationMap *refs = new ObjectAssociationMap;
 associations[disguised_object] = refs;
 (*refs)[key] = ObjcAssociation(policy, new_value);
object->setHasAssociatedObjects();

inline void
objc_object::setHasAssociatedObjects()
{
    ...
    newisa.has_assoc = true;//关联对象标志位
    if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
}

ObjcAssociation是构造存储对象。
即一个对象会生成一个ObjectAssociationMap,并通过disguised_object存储在associations中,new_value存储在ref中,setHasAssociatedObjects设置对象有关联对象的标志位。
refs存储当前对象的所有关联对象

  1. associations已经分配时,通过key进行存储
ObjectAssociationMap *refs = i->second;
ObjectAssociationMap::iterator j = refs->find(key);
if (j != refs->end()) {
     old_association = j->second;
     j->second = ObjcAssociation(policy, new_value);//key已经存在时,找到对应位置更新旧的
} else {
     (*refs)[key] = ObjcAssociation(policy, new_value);//key没有存储时,直接存储
}

如果key存储过值,找到对应的value的位置,替换旧的。
如果key没有,ObjcAssociation构造的对象。

关联对象存储分三种情况:
第一种:对象第一次使用关联对象初始化,ObjectAssociationMap,使用策略和value构造存储对象
第二种:对象的关联对象已经初始化,在ObjectAssociationMap查找,没找到按key直接存储。
第三种:对象的关联对象已经初始化,在ObjectAssociationMap查找,找到按key替换原有的存储。

2.2 objc_getAssociatedObject

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

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

这一段在associations查找,如果策略是OBJC_ASSOCIATION_GETTER_RETAIN,会有个计数+1objc_retain(value);如果是OBJC_ASSOCIATION_GETTER_AUTORELEASE,通过objc_autorelease延迟释放。

2.3objc_removeAssociatedObjects

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

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

这个方法在dealloc中通过hasAssociatedObjects标志位释放,
找到关联对象elements,遍历进行释放。

总结:
1.不用修改原有对象就能为其添加属性,不消耗对象分配空间。
2.关联对象释放不用担心,系统会在对象销毁时在dealloc中根据标志位进行释放。
3.关联对象与分类的关系?关联对象很好的解决了分类不能添加属性的问题。
4.关联对象的本质:由AssociationsManager管理并在AssociationsHashMap存储。
所有对象的关联内容都在同一个全局容器中。

上一篇 下一篇

猜你喜欢

热点阅读