美文网首页📚苹果
系统底层源码分析(9)——Category(分类)关联属性

系统底层源码分析(9)——Category(分类)关联属性

作者: 无悔zero | 来源:发表于2021-05-29 06:48 被阅读0次

    之前了解了分类的编译与运行和一些知识,其中提到分类不能直接加属性,今天就来看看分类怎么添加属性的,直接看例子:

    #import <objc/runtime.h>
    
    @implementation Person (Test)
    
    - (void)setName:(NSString*)name{
        objc_setAssociatedObject(self, @"NameKey", name, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    
    - (NSString*)name{
        return objc_getAssociatedObject(self, @"NameKey");
    }
    
    @end
    
    • 设置
    1. objc4-750源码探究,先来看设置:
    //通过 key : value 的形式给对象 object 设置关联属性
    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());//初始化 HashMap
            
            disguised_ptr_t disguised_object = DISGUISE(object);//当前对象的地址按位取反后作为key
            if (new_value) {
                // break any existing association.
                AssociationsHashMap::iterator i = associations.find(disguised_object);//<fisrt : disguised_object , second : ObjectAssociationMap> 类似于元组,存着所有关联属性的键值对
                if (i != associations.end()) {
                    // secondary table exists
                    ObjectAssociationMap *refs = i->second;//一个对象的所有关联属性键值对
                    ObjectAssociationMap::iterator j = refs->find(key);//<fisrt : 标识(自定义的) , second : ObjcAssociation>
                    if (j != refs->end()) {
                        old_association = j->second;//新值覆盖
                        j->second = ObjcAssociation(policy, new_value);//ObjcAssociation存放关联属性
                    } else {
                        (*refs)[key] = ObjcAssociation(policy, new_value);
                    }
                } else {
                    // create the new association (first time).
                    ObjectAssociationMap *refs = new ObjectAssociationMap;
                    associations[disguised_object] = refs;
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                    
                    object->setHasAssociatedObjects();//设置当前的isa指针
                }
            } else { ... }
        }
        // release the old value (outside of the lock).
        if (old_association.hasValue()) ReleaseValue()(old_association);
    }
    

    AssociationsManager里存着AssciationsHashMap
    AssciationsHashMap里存着<fisrt : disguised_ptr_t , second : ObjectAssociationMap>
    ObjectAssociationMap里存着<fisrt : 标识(自定义的) , second : ObjcAssociation>
    ObjcAssociation里存着策略policy和值value
    所以最终关联属性就是存放在ObjcAssociation里。

    • 获取
    1. 然后获取自然也是从ObjcAssociation类里获取:
    //通过 key 获取关联的属性 object
    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;
    }
    
    • 销毁
    1. 当对象销毁时,关联属性也随之销毁:
    - (void)dealloc {
        _objc_rootDealloc(self);
    }
    
    void
    _objc_rootDealloc(id obj)
    {
        assert(obj);
    
        obj->rootDealloc();
    }
    
    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<ObjcAssociation> > elements;
        {
            AssociationsManager manager;
            AssociationsHashMap &associations(manager.associations());
            if (associations.size() == 0) return;
            disguised_ptr_t disguised_object = DISGUISE(object);//key
            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());//移除
    }
    
    1. 当然也可以手动移除:
    //移除对象所关联的属性
    void objc_removeAssociatedObjects(id object) 
    {
        if (object && object->hasAssociatedObjects()) {
            _object_remove_assocations(object);
        }
    }
    

    分类关联属性其实就是利用它的AssociationsManager管理保存在ObjcAssociation里的关联属性。

    相关文章

      网友评论

        本文标题:系统底层源码分析(9)——Category(分类)关联属性

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