objc_setAssociatedObject
属性关联可以在运行时动态的给某个对象添加属性,来看objc_setAssociatedObject的实现:
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) {
_object_set_associative_reference(object, (void *)key, value, policy);
}
_object_set_associative_reference函数首先初始化了一个ObjcAssociation对象
ObjcAssociation old_association(0, nil)
old_association用来存储关联的值和关联策略,默认是OBJC_ASSOCIATION_ASSIGN。接下来如果发现传入的value不为空,那么就对传入的value进retain或者copy操作(如果关联策略是OBJC_ASSOCIATION_SETTER_RETAIN或者OBJC_ASSOCIATION_SETTER_COPY)
id new_value = value ? acquireValue(value, policy) : nil;
//acquireValue函数的实现
static id acquireValue(id value, uintptr_t policy) {
switch (policy & 0xFF) {
case OBJC_ASSOCIATION_SETTER_RETAIN:
return ((id(*)(id, SEL))objc_msgSend)(value, SEL_retain);
case OBJC_ASSOCIATION_SETTER_COPY:
return ((id(*)(id, SEL))objc_msgSend)(value, SEL_copy);
}
return value;
}
接下来初始化AssociationsManager,AssociationsManager里面主要是存在一个hash map,结构如下:
class AssociationsManager {