iOS-Developer-OCiOS - Developer - OC 进阶大全

Object-C关联对象

2019-08-01  本文已影响1人  zwwuchn

什么是关联对象

关联对象是指某个对象通过唯一的key连接到一个类的实例上

runtime提供的方法
//关联对象
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
//获取关联的对象
id objc_getAssociatedObject(id object, const void *key)
//移除关联的对象
void objc_removeAssociatedObjects(id object)
// 被关联的对象
id object
// 关联的key,要求唯一
const void *key
// 关联的对象
id value
// 相当于 setValue:forKey 进行关联value对象
objc_setAssociatedObject 
// 用来读取对象
objc_getAssociatedObject 
// 属性是设定该value在object内的属性,即 assgin, (retain,nonatomic)...等
objc_AssociationPolicy  
关联策略: 五种关联策略。
OBJC_ASSOCIATION_ASSIGN 等价于 @property(assign)。
OBJC_ASSOCIATION_RETAIN_NONATOMIC等价于 @property(strong, nonatomic)。
OBJC_ASSOCIATION_COPY_NONATOMIC等价于@property(copy, nonatomic)。
OBJC_ASSOCIATION_RETAIN等价于@property(strong,atomic)。
OBJC_ASSOCIATION_COPY等价于@property(copy, atomic)。
// 函数来移除一个关联对象,或者使用objc_setAssociatedObject函数将key指定的关联对象设置为nil。
 objc_removeAssociatedObjects
举例说明
@interface LPPerson : NSObject
@property (nonatomic,copy) NSString *name;
@end
@implementation LPPerson
@end

@interface LPPerson (Test)
@property (nonatomic,assign) int age;
@end
- (int)age {
    
    // Key可以有多种写法
    
    // ① 私有变量: static const void *MJNameKey = &MJNameKey;
    return [objc_getAssociatedObject(self, &LPAgeKeys) intValue];
    // ② 宏定义Key: #define LPAgeKey @"age"
    return [objc_getAssociatedObject(self, LPAgeKey) intValue];
    // ③ @selector(age): 返回结构体指针
    return [objc_getAssociatedObject(self, @selector(age)) intValue];
    // ④ 隐式参数: _cmd == @selector(age)
    return [objc_getAssociatedObject(self, _cmd) intValue];
}
- (void)setAge:(int)age {

    objc_setAssociatedObject(self, &LPAgeKeys, @(age), OBJC_ASSOCIATION_ASSIGN);
    objc_setAssociatedObject(self, LPAgeKey, @(age), OBJC_ASSOCIATION_ASSIGN);;
    objc_setAssociatedObject(self, @selector(age), @(age), OBJC_ASSOCIATION_ASSIGN);
    // get方法_cmd等价@selector(age),而set方法_cmd等价@selector(setAge:)
    objc_setAssociatedObject(self, @selector(age), @(age), OBJC_ASSOCIATION_ASSIGN);
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        LPPerson *person = [[LPPerson alloc] init];
        person.name = @"jack";
        person.age = 18;
        NSLog(@"This is %@, age is %d",person.name,person.age);
        
        LPPerson *person2 = [[LPPerson alloc] init];
        person2.name = @"rose";
        person2.age = 16;
        NSLog(@"This is %@, age is %d",person2.name,person2.age);
        
    }
    return 0;
}
// 打印:
This is jack, age is 18
This is rose, age is 16

关联对象内部数据结构

实现关联对象的核心对象

AssociationsManager代码定义

class AssociationsManager {
    static AssociationsHashMap *_map;
};
class AssociationsHashMap : public unordered_map<disguised_ptr_t, ObjectAssociationMap *, DisguisedPointerHash, DisguisedPointerEqual, AssociationsHashMapAllocator>

class ObjectAssociationMap : public std::map<void *, ObjcAssociation, ObjectPointerLess, ObjectAssociationMapAllocator>

class ObjcAssociation {
        uintptr_t _policy;
        id _value;
};
一幅图看破一切
图片.png
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;
        // 通过AssociationsManager获得AssociationsHashMap
        AssociationsHashMap &associations(manager.associations());
        // 生成key
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // 遍历查找AssociationsHashMap
            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()) {
                // 通过AssociationsHashMap查找ObjcAssociation
                    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);
}
上一篇下一篇

猜你喜欢

热点阅读