面试

Category底层实现分析4 - 关联对象Associated

2018-08-30  本文已影响18人  Jacob_LJ

注:分析参考 MJ底层原理班 内容,本着自己学习原则记录

本文使用的源码为objc4-723

1 Category中不可以添加成员变量

1.1 对比 Category 和 NSObject 在 C++ 的结构体形式可知,Category 中不具有保存成员变量(iVars)的列表成员变量

  1. 实例对象结构objc_object 和 类对象、元类对象结构objc_class成员中都具有ivar_list_t *ivars(成员变量存放列表),可参考文章的第3.8.2点
objc_class
  1. struct _category_t中不具有成员变量存放列表的相关字段
    struct _category_t

1.2 但可以写上@property 属性,但编译器仅仅会生成属性的 getter、setter 方法的声明

2 通过关联对象(AssociatedObject)给分类添加成员变量

2.1 关联对象常用API

  1. 添加关联对象
    void objc_setAssociatedObject(id object, const void * key, id value, objc_AssociationPolicy policy)

参数:
id object :需要设置关联属性的对象,如想给 person 实例关联属性 name的值,那么 object 即为 person 对象。
const void * key:关联属性值对应的 key,(内部实现的原理就是基于类似于字典的hashmap)
id value:关联给指定对象属性的值
objc_AssociationPolicy policy:关联策略,其中对应@property 的内存语义关键字如下图:

图片引自 MJ 底层课课件
  1. 获得关联对象
    id objc_getAssociatedObject(id object, const void * key)

  2. 移除所有的关联对象
    void objc_removeAssociatedObjects(id object)

2.2 基本使用形式

// Person+Test.h
@interface Person (Test)
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) int weight;
@end


// Person+Test.m
#import "Person+Test.h"
#import <objc/runtime.h>

@implementation Person (Test)
- (void)setName:(NSString *)name {
    objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)name {
    return objc_getAssociatedObject(self, @selector(name));
}


- (void)setWeight:(int)weight {
    objc_setAssociatedObject(self, @selector(weight), @(weight), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (int)weight {
    return [objc_getAssociatedObject(self, @selector(weight)) intValue];
}
@end

上面代码中,通过@selector包装getter 方法传入给const void * key,使用这种形式的有点有:

  1. 敲该方法是具有编译器提示功能
  2. 统一了一个属性的 setter、getter 中objc_setAssociatedObjectobjc_getAssociatedObject函数中使用的 key,当然你使用@selector来包装 setter 方法也是可以,只不过稍微长一点
  3. 同时也符合参数 const void * key类型的要求,@selector包装getter方法返回的类型是 SEL,SEL 的定义是typedef struct objc_selector *SEL;,即SEL 代表是一个结构体,也就是说将该结构体的指针传入到 const void * key参数中。

注意,只要能保证 key 这个参数对应关联对象来说是唯一的就行其 set 和 get 时候都使用同一个 key 的话,你也可以传入一个字符串常量,或其他 void * 的指针类型。

3 AssociatedObject关联对象的实现底层分析

3.1 在runtime源码中直接搜索objc_setAssociatedObject

3.2 _object_get_associative_reference 的实现

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

3.3 _object_set_associative_reference 的实现

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

3.4 _object_remove_assocations 的实现

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

3.5 基于上述源码,实现关联对象技术的核心对象和关系为

3.5.1 核心对象

3.5.2 它们的关系

对应的方法objc_setAssociatedObject参数

void objc_setAssociatedObject(
                              id object, const void * key,
                              id value, 
                              objc_AssociationPolicy policy
                            );
图片引自 MJ 底层课课件

文/Jacob_LJ(简书作者)
PS:如非特别说明,所有文章均为原创作品,著作权归作者所有,转载需联系作者获得授权,并注明出处,所有打赏均归本人所有!

上一篇下一篇

猜你喜欢

热点阅读