2、关联对象知识点整理

由于分类是不能直接添加成员变量的,因此需要使用关联对象技术为分类添加成员变量,由此引出几个问题:

  • 问题1❓:什么是成员变量,成员变量和实例变量还有属性的区别是什么?
  • 问题2❓:分类中是如何添加成员变量的,其实现原理是什么?
  • 问题3❓:分类中添加的成员变量被保存在哪?(在宿主类上还是其他什么地方)
void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {

    //1.创建一个空的ObjcAssociation对象
    ObjcAssociation old_association(0, nil);

    // 2.对关联对象进行内存管理操作retain/copy
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        //3.创建AssociationsManager对象和其成员变量AssociationsHashMap对象
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        
        //4.将被关联对象的指针地址反转
        disguised_ptr_t disguised_object = DISGUISE(object);

        // 5.判断传入的关联对象是否为空
        if (new_value) {
             //如果不为空
             /*通过被关联对象的指针地址从AssociationsHashMap中获取对应的      
              ObjectAssociationMap
            */
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            //如果该被关联对象已经存在了对应的ObjectAssociationMap
            if (i != associations.end()) {
                // 通过参数key获取到ObjectAssociationMap对应的ObjcAssociation
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                //如果存在对应的ObjcAssociation
                if (j != refs->end()) {
                    //把开始创建的空的ObjcAssociation对象设置为找到的这个ObjcAssociation
                    old_association = j->second;
                    //把当前的关联对象封装为ObjcAssociation并赋值给ObjectAssociationMap中key对应的值
                    j->second = ObjcAssociation(policy, new_value);
                } else {//如果没有找到存在对应的ObjcAssociation,那就根据参数key直接设置
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                }
            } else { //如果该被关联对象不存在了对应的ObjectAssociationMap
                // 那么就创建新的ObjectAssociationMap
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                //以被关联对象的反转地址为key,新创建的ObjectAssociationMap为value,映射为ObjectAssociationHashMap
                associations[disguised_object] = refs;
                //把参数key作为ObjectAssociationMap的key,ObjcAssociation对象为value
                (*refs)[key] = ObjcAssociation(policy, new_value);
                //最后设置这个被关联对象为有关联对象
                object->setHasAssociatedObjects();
            }
        } else {//如果传入的关联对象为nil,会将被关联对象的对应关联对象擦除
            // setting the association to nil breaks the association.
            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);
                }
            }
        }
    }
    // 最后将old_association擦除
    if (old_association.hasValue()) ReleaseValue()(old_association);
}

id _object_get_associative_reference(id object, void *key) {
    id value = nil;
    uintptr_t policy = OBJC_ASSOCIATION_ASSIGN;
    {
        AssociationsManager manager;
        // 初始化hashmap
        AssociationsHashMap &associations(manager.associations());
        // 当前对象的地址按位取反(key)
        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;
}

inline void
objc_object::setHasAssociatedObjects()
{
    if (isTaggedPointer()) return;

 retry:
    // 设置当前的isa指针的标识
    isa_t oldisa = LoadExclusive(&isa.bits);
    isa_t newisa = oldisa;
    if (!newisa.nonpointer  ||  newisa.has_assoc) {
        ClearExclusive(&isa.bits);
        return;
    }
    newisa.has_assoc = true;
    if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
}

inline void
objc_object::rootDealloc()
{
    if (isTaggedPointer()) return;  // fixme necessary?

    if (fastpath(isa.nonpointer  &&  
                 !isa.weakly_referenced  &&  
                 !isa.has_assoc  &&  
                 !isa.has_cxx_dtor  &&  
                 !isa.has_sidetable_rc))
    {
        assert(!sidetable_present());
        free(this);
    } 
    else {
        object_dispose((id)this);
    }
}

id 
object_dispose(id obj)
{
    if (!obj) return nil;

    objc_destructInstance(obj);    
    free(obj);

    return nil;
}

void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_assocations(obj);
        obj->clearDeallocating();
    }

    return obj;
}

void _object_remove_assocations(id object) {
    vector< ObjcAssociation,ObjcAllocator > 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());
}

关联对象并不是存储在被关联对象本身内存中,而是存储在全局的统一的一个AssociationsManager中,如果设置关联对象为nil,就相当于是移除关联对象。

你可能感兴趣的:(2、关联对象知识点整理)