发布于 

Associated Objects 实现原理

在上一篇《Category 梳理》里面提到 Category 可以添加实例方法、添加类方法、添加协议,但是不能添加属性。原因是 objc_category 结构体中没有属性(实例)列表,即使我们声明了属性,编译器也不会帮我们生成对应的 setter/getter。所以这种情况下,如果调用这些属性,会出现崩溃的情况。但这个问题是可以解决的。OC 是一门动态语言,方法真正的实现是通过 runtime 来完成的,虽然系统未给我们生成 setter/getter,但我们可以通过 runtime 来手动添加需要的 setter/getter 方法。即引申除了将要梳理的 Associated Objects

Associated Objects(关联对象)可以给类动态的添加实例变量,可以增强类结构的灵活性。

如何使用

应用示例代码:

1
2
3
4
5
#import <Foundation/Foundation.h>

@interface NSObject (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#import "NSObject+AssociatedObject.h"
#import <objc/runtime.h>

static const char kAssociatedObject;

@implementation NSObject (AssociatedObject)

- (id)associatedObject {
return objc_getAssociatedObject(self, &kAssociatedObject);
}

- (void)setAssociatedObject:(id)associatedObject {
objc_setAssociatedObject(self, &kAssociatedObject, associatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

核心函数方法:

  • objc_setAssociatedObject:可以为一个对象设置一个关联对象
  • objc_getAssociatedObject:获取一个对象的关联对象
  • objc_removeAssociatedObjects:移除一个关联对象

源码实现

已经知道了对象的关联代码,那是怎么关联的呢?看下对应的源码实现。

objc_setAssociatedObject

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

进入 objc_setAssociatedObject 方法后,看到其内部调用了 _object_set_associative_reference 方法。源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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.
// 如果设置新的 value 非 nil
// 首先查看被关联对象的 AssociationHashMap 是否存在
// 若存在,去更新;
// 若不存在,则新建 ObjectAssociationMap,并加入 key-value 映射
// 同时,setHasAssociatedObjects()
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.
// 若 value 为 nil,移除关联对象
// old_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);
}

注释大概描述了 _object_set_associative_reference 的实现过程,再来细看下涉及到方法和数据结构。

acquireValue()

1
2
3
4
5
6
7
8
9
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;
}

根据关联策略对应处理对象,将处理结果返回。

AssociationsManager

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}
};

AssociationsManager 是一个管理对象,维护一个带锁的 **AssociationsHashMap**,构造函数加锁,析构函数解锁。

AssociationsHashMap

1
2
3
4
// ...
ObjectAssociationMap *refs = new ObjectAssociationMap;
associations[disguised_object] = refs;
// ...

是一个无序 hash 表。key 是对象的地址;value 是 **ObjectAssociationMap**。

ObjectAssociationMap

1
2
3
4
5
6
7
8
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);
}

是一个无序 hash 表。key 是我们传入的 key;value 是 **ObjcAssociation**。

ObjcAssociation

1
2
3
4
5
6
7
8
9
10
11
12
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; }
};

是一个关联对象的封装。里面维护了关联对象的值(value)和关联策略(policy)。

objc_getAssociatedObject

objc_getAssociatedObject 内部调用 **_object_get_associative_reference**。源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
}

_object_get_associative_reference() 首先通过对象指针获取 AssociationsHashMap;再通过 key 在 ObjectAssociationMap 里获取对应的 ObjcAssociation 并取到 value 和 policy;根据 policy 对应调用 objc_retain()objc_autorelease()

objc_removeAssociatedObjects

1
2
3
4
5
6
void objc_removeAssociatedObjects(id object) 
{
if (object && object->hasAssociatedObjects()) {
_object_remove_assocations(object);
}
}

objc_removeAssociatedObjects 内部会先判断对象是否有关联对象,若有则调用 **_object_remove_assocations()**。对应源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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());
}

即遍历取到所有的 AssociationsHashMap,并释放。

释放机制

涉及到对象释放,我们首先想到的即为 dealloc,逐步看下 dealloc 过程中,是如何释放 assocations 的。

dealloc() 源码:

1
2
3
- (void)dealloc {
_objc_rootDealloc(self);
}

_objc_rootDealloc() 源码:

1
2
3
4
5
6
7
void
_objc_rootDealloc(id obj)
{
assert(obj);

obj->rootDealloc();
}

rootDealloc() 源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
}
}

object_dispose() 源码:

1
2
3
4
5
6
7
8
9
10
id 
object_dispose(id obj)
{
if (!obj) return nil;

objc_destructInstance(obj);
free(obj);

return nil;
}

objc_destructInstance() 源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}

到这里会看到我们熟悉的 **hasAssociatedObjects()**,如果对象有关联对象,则将他们释放。

参考阅读:


本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

本站由 @JonyFang 创建,使用 Stellar 作为主题,您可以在 GitHub 找到本站源码。