前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >OC - Association 关联对象

OC - Association 关联对象

作者头像
师大小海腾
发布2020-04-16 17:28:04
1.3K0
发布2020-04-16 17:28:04
举报

目录

  • 1. 关联对象 1.1 使用场景 1.2 使用方法  1.2.1 相关 API  1.2.2 objc_AssociationPolicy 关联策略  1.2.3 key 的常见用法
  • 2. 关联对象的原理
  • 3. 相关面试题

1. 关联对象

1.1 使用场景

默认情况下,由于分类底层结构的限制,不能直接给 Category 添加成员变量,但是可以通过关联对象间接实现 Category 有成员变量的效果。

传送门:OC - Category 和 Extension

1.2 使用方法

#import "Person.h"
@interface Person (Test)
@property (nonatomic, assign) int height;
@end

#import "Person+Test.h"
#import <objc/runtime.h>
@implementation Person (Test)
- (void)setHeight:(int)height
{
    objc_setAssociatedObject(self, @selector(height), [NSNumber numberWithInt:height], OBJC_ASSOCIATION_ASSIGN);
}
- (int)height
{
    return [objc_getAssociatedObject(self, @selector(height)) intValue];
}
@end
1.2.1 相关 API

objc_setAssociatedObject

使用给定的key和关联策略为给定的对象设置关联的value

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

objc_getAssociatedObject

返回给定key的给定对象关联的value

id objc_getAssociatedObject(id object, const void *key);

objc_removeAssociatedObjects

删除给定对象的所有关联。

void objc_removeAssociatedObjects(id object);

如果只想移除给定对象的某个key的关联,可以使用objc_setAssociatedObject的给参数value传值nil

objc_setAssociatedObject(self, @selector(height), nil, OBJC_ASSOCIATION_ASSIGN);
1.2.2 objc_AssociationPolicy 关联策略
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};

objc_AssociationPolicy

对应的属性修饰符

OBJC_ASSOCIATION_ASSIGN

assign

OBJC_ASSOCIATION_RETAIN_NONATOMIC

strong, nonatomic

OBJC_ASSOCIATION_COPY_NONATOMIC

copy, nonatomic

OBJC_ASSOCIATION_RETAIN

strong, atomic

OBJC_ASSOCIATION_COPY

copy, atomic

1.2.3 key 的常见用法
// ①
static const void *MyKey = &MyKey;
objc_setAssociatedObject(object, MyKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_getAssociatedObject(object, MyKey];

// ② 
static const char MyKey;
objc_setAssociatedObject(object, &MyKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_getAssociatedObject(object, &MyKey];

// ③ 使用属性名作为 key
#define MYHEIGHT @"height"
objc_setAssociatedObject(object, MYHEIGHT, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_getAssociatedObject(object, MYHEIGHT];

// ④ 使用 getter 方法的 SEL 作为 key(可读性高,有智能提示)
objc_setAssociatedObject(object, @selector(getter), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_getAssociatedObject(object, @selector(getter)];
// 或使用隐式参数 _cmd
objc_getAssociatedObject(object, _cmd];

2. 关联对象的原理

Runtime源码objc4中,有关关联对象的代码都在文件objc-references.mm中。

实现关联对象技术的核心对象

  • AssociationsManager
  • AssociationsHashMap
  • ObjectAssociationMap
  • ObjcAssociation
class AssociationsManager {
    static AssociationsHashMap *_map;
};
class AssociationsHashMap : public unordered_map<disguised_ptr_t, ObjectAssociationMap>
class ObjectAssociationMap : public std::map<void *, ObjcAssociation>
class ObjcAssociation {
    uintptr_t _policy;
    id _value;
};

AssociationsManager

  • 关联对象并不是存储在关联对象本身内存中,而是存储在全局统一的一个容器中;
  • 由 AssociationsManager 管理并在它维护的一个单例 Hash 表 AssociationsHashMap 中存储;
  • 使用 AssociationsManagerLock 自旋锁保证了线程安全。
class AssociationsManager {
    // associative references: object pointer -> PtrPtrHashMap.
    static AssociationsHashMap *_map;
public:
    AssociationsManager()   { AssociationsManagerLock.lock(); }
    ~AssociationsManager()  { AssociationsManagerLock.unlock(); }
    
    AssociationsHashMap &associations() {
        if (_map == NULL)
            _map = new AssociationsHashMap();
        return *_map;
    }
};

AssociationsHashMap

  • 一个单例的 Hash 表,存储 disguised_ptr_t 和 ObjectAssociationMap 之间的映射。
  • disguised_ptr_t 是根据 object 生成,但不存在引用关系。 disguised_ptr_t disguised_object = DISGUISE(object);
class AssociationsHashMap : public unordered_map<disguised_ptr_t, ObjectAssociationMap *, DisguisedPointerHash, DisguisedPointerEqual, AssociationsHashMapAllocator> {
public:
    void *operator new(size_t n) { return ::malloc(n); }
    void operator delete(void *ptr) { ::free(ptr); }
};

ObjectAssociationMap

  • 存储 key 和 ObjcAssociation 之间的映射。
class ObjectAssociationMap : public std::map<void *, ObjcAssociation, ObjectPointerLess, ObjectAssociationMapAllocator> {
public:
    void *operator new(size_t n) { return ::malloc(n); }
    void operator delete(void *ptr) { ::free(ptr); }
};

ObjcAssociation

  • 存储着关联策略 policy 和关联对象的值 value。
class ObjcAssociation {
    uintptr_t _policy;
    id _value;
public:
    ObjcAssociation(uintptr_t policy, id value) : _policy(policy), _value(value) {}
    ObjcAssociation() : _policy(0), _value(nil) {}

    uintptr_t policy() const { return _policy; }
    id value() const { return _value; }
    
    bool hasValue() { return _value != nil; }
};

objc_setAssociatedObject

  • ① 实例化一个 AssociationsManager 对象,它维护了一个单例 Hash 表 AssociationsHashMap 对象;
  • ② 实例化一个 AssociationsHashMap 对象,它维护 disguised_ptr_t 和 ObjectAssociationMap 对象之间的关系;
  • ③ 根据object生成一个 disguised_ptr_t 对象;
  • ④ 根据 disguised_ptr_t 获取对应的 ObjectAssociationMap 对象,它存储key和 ObjcAssociation 之间的映射;
  • ⑤ 根据policyvalue创建一个 ObjcAssociation 对象,并存储在 ObjectAssociationMap 中;
  • ⑥ 如果传进来的value为 nil,则在 ObjectAssociationMap 中删除该 ObjcAssociation 对象。
// objc-runtime.mm
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) {
    _object_set_associative_reference(object, (void *)key, value, policy);
}

// objc-references.mm
void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {
    // This code used to work when nil was passed for object and key. Some code
    // probably relies on that to not crash. Check and handle it explicitly.
    // rdar://problem/44094390
    // 判空操作
    if (!object && !value) return;
    
    assert(object);
    
    if (object->getIsa()->forbidsAssociatedObjects())
        _objc_fatal("objc_setAssociatedObject called on instance (%p) of class %s which does not allow associated objects", object, object_getClassName(object));
    
    // retain the new value (if any) outside the lock.
    ObjcAssociation old_association(0, nil);
    // 判断传进来的 value 是否为 nil?如果有值则调用 acquireValue(value, policy)
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        /*
         ** 初识化一个 AssociationsManager 对象
         ** 它维护了一个单例 Hash 表 AssociationsHashMap 对象
         */
        AssociationsManager manager;
        /*
         ** 初识化一个 AssociationsHashMap (单例)对象
         ** 它维护 disguised_ptr_t 和 ObjectAssociationMap 对象之间的关系
         */
        AssociationsHashMap &associations(manager.associations());
        // 根据传进来的 object 生成一个 key(disguised_ptr_t对象), 不存在和 object 的引用关系
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // break any existing association.
            // 根据 key(disguised_object) 从 AssociationsHashMap 中获取遍历器i
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i != associations.end()) {
                // secondary table exists
                /*
                 ** 根据遍历器i获取到 ObjectAssociationMap
                 ** i->first 表示对象地址
                 ** i->second 表示获取 ObjectAssociationMap
                 */
                ObjectAssociationMap *refs = i->second;
                // 根据传进来的 key 从 ObjectAssociationMap 中获取遍历器j
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    // 根据传进来的 policy 和 value 创建 ObjcAssociation
                    // 若关联对象已存在,则赋新值
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    // 若关联对象不存在,则创建新的关联对象
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                }
            } else {
                // create the new association (first time).
                /*
                 ** 若没有传进来的 object 对应的 ObjectAssociationMap 表,就创建
                 */
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                associations[disguised_object] = refs;
                (*refs)[key] = ObjcAssociation(policy, new_value);
                object->setHasAssociatedObjects();
            }
        /*
         ** 如果传进来的 value 为 nil,则删除该关联对象
         ** 调用 erase(j) 函数对 j 进行擦除
         ** 即在 ObjectAssociationMap 中擦除传进来的 key(key) 和它所对应的 ObjcAssociation(value)
         ** 所以,如果想移除给定对象的某个 key 的关联,可以使用 objc_setAssociatedObject 给参数 value 传值 nil。
         */
        } 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);
}

objc_getAssociatedObject

  • ① 实例化一个 AssociationsManager 对象;
  • ② 实例化一个 AssociationsHashMap 对象;
  • ③ 根据object生成一个 disguised_ptr_t 对象;
  • ④ 根据 disguised_ptr_t 获取对应的 ObjectAssociationMap 对象;
  • ⑤ 根据 key 获取到它所对应的 ObjcAssociation 对象;
  • ⑥ 返回 ObjcAssociation 中的 value。
// objc-runtime.mm
id objc_getAssociatedObject(id object, const void *key) {
    return _object_get_associative_reference(object, (void *)key);
}

// objc-references.mm
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;
}

objc_removeAssociatedObjects

  • ① 实例化一个 AssociationsManager 对象;
  • ② 实例化一个 AssociationsHashMap 对象;
  • ③ 根据object生成一个 disguised_ptr_t 对象;
  • ④ 根据 disguised_ptr_t 获取对应的 ObjectAssociationMap 对象;
  • ⑤ 删除该 ObjectAssociationMap 对象。
// objc-runtime.mm
void objc_removeAssociatedObjects(id object) 
{
    if (object && object->hasAssociatedObjects()) {
        _object_remove_assocations(object);
    }
}

// objc-references.mm
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;
            /* 调用 erase(i) 函数对 i 进行擦除
               即在 AssociationsHashMap 中擦除传进来的 object(key) 和它所对应的 ObjectAssociationMap(value)
               所以,如果想删除给定对象的所有关联,调用 objc_removeAssociatedObjects 函数即可
             */
            associations.erase(i);
        }
    }
    // the calls to releaseValue() happen outside of the lock.
    for_each(elements.begin(), elements.end(), ReleaseValue());
}

acquireValue

根据policy来对value进行retain或者copy操作。

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

3. 相关面试题

Q:如何移除关联对象?
  • 移除一个object的某个key的关联对象:调用objc_setAssociatedObject设置关联对象valuenilobjc_setAssociatedObject函数会调用_object_set_associative_reference函数,并在该函数中判断传进来的value是否为nil,是的话会调用erase(j)擦除函数,将j变量擦除。j即为ObjectAssociationMap对象里的一对【key: key value: ObjcAssociation(_policy、_value)】。
  • 移除一个object的所有关联对象:调用函数objc_removeAssociatedObjectsobjc_removeAssociatedObjects函数会调用_object_remove_assocations函数,并在该函数中调用对象的erase(i)擦除函数,将i变量擦除。i即为AssociationsHashMap对象中的一对【key: object value: ObjectAssociationMap】。
Q:如果 object 被销毁,那它所对应的 ObjectAssociationMap 是否也会自动销毁?

答案是肯定的。

Q:如果没有关联对象,怎么实现 Category 有成员变量的效果?

使用字典。创建一个全局的字典,将self对象在内存中的地址作为key

缺点:① 内存泄漏问题:全局变量会一直存储在内存中;

   ② 线程安全问题:可能会有多个对象同时访问字典,加锁可以解决;

   ③ 每添加一个成员变量就要创建一个字典,很麻烦。

#import "Person.h"
@interface Person (Test)
@property (nonatomic, assign) int height;
@end

#import "Person+Test.h"
#import <objc/runtime.h>
@implementation Person (Test)
NSMutableDictionary *heights_;
+ (void)load {
    heights_ = [NSMutableDictionary dictionary];
}
- (void)setHeight:(int)height {
    NSString *key = [NSString stringWithFormat:@"%@",self];
    heights_[key] = @(height);
}
- (int)height {
    NSString *key = [NSString stringWithFormat:@"%@",self];
    return [heights_[key] intValue];
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 关联对象
    • 1.1 使用场景
      • 1.2 使用方法
        • 1.2.1 相关 API
        • 1.2.2 objc_AssociationPolicy 关联策略
        • 1.2.3 key 的常见用法
        • Q:如何移除关联对象?
        • Q:如果 object 被销毁,那它所对应的 ObjectAssociationMap 是否也会自动销毁?
        • Q:如果没有关联对象,怎么实现 Category 有成员变量的效果?
    • 2. 关联对象的原理
    • 3. 相关面试题
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档