Objective-C 使用关联对象给Category添加属性

实现过程

  • 在类中声明属性,会生成setter、getter、成员变量
  • 在分类中声明属性,只会生成setter个getter,不会生成成员变量
  • 从分类的底层结构也可以看出,没有成员变量的属性
struct category_t {
    const char *name;
    classref_t cls;
    struct method_list_t *instanceMethods; /// 实例方法列表
    struct method_list_t *classMethods; /// 类方法列表
    struct protocol_list_t *protocols;  // 协议列表
    struct property_list_t *instanceProperties; // 实例属性列表
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties;
    
    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }
    
    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};
  • 但可以通过关联对象来简介实现成员变量
// 添加关联对象
void objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
                         id _Nullable value, objc_AssociationPolicy policy)
// 获取关联对象
id objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
// 移除所有的关联对象
void objc_removeAssociatedObjects(id _Nonnull object)
  • 完整代码如下
@interface MJPerson (Associate)
@property (nonatomic, copy) NSString *nickiname;

@end

@implementation MJPerson (Associate)
- (void)setNickiname: (NSString*)nickiname {
    objc_setAssociatedObject(self, @selector(nickiname), nickiname, OBJC_ASSOCIATION_COPY);
}

- (NSString*)nickiname {
    return objc_getAssociatedObject(self, @selector(nickiname));
}
@end
  • 关联对象所需要的key常见写法如下:
    • 使用地址值作为Key
      static void *MyKey = &MyKey;
      objc_setAssociatedObject(obj, MyKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
      objc_getAssociatedObject(obj, MyKey)
    
    static char MyKey;
    objc_setAssociatedObject(obj, &MyKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    objc_getAssociatedObject(obj, &MyKey)
    
    • 使用属性名作为key
    objc_setAssociatedObject(obj, @"property", value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_getAssociatedObject(obj, @"property");
    
    • 使用get方法的@selecor作为key
    objc_setAssociatedObject(obj, @selector(getter), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    objc_getAssociatedObject(obj, @selector(getter))
    
  • objc_AssociationPolicy对应的修饰符


    image.png

关联对象实现属性的原理,源码解读

  • 实现关联对象技术的核心对象有:
    • AssociationsManager负责处理 AssociationsHashMap的存储逻辑
    • AssociationsHashMap保存程序中所有的被关联对象(键值对的形式存储)
    • ObjectAssociationMap保存被关联对象的所有属性(键值对的形式存储)
    • ObjcAssociation保存被关联对象的某一个属性值
  • objc4源码解读,objc-reference.mm
    class AssociationsManager {
      // associative references: object pointer -> PtrPtrHashMap.
      static AssociationsHashMap *_map;
      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;
        }
    };
    class AssociationsHashMap : public unordered_map {
      public:
          void *operator new(size_t n) { return ::malloc(n); }
          void operator delete(void *ptr) { ::free(ptr); }
      };
     class ObjectAssociationMap : public std::map {
      public:
          void *operator new(size_t n) { return ::malloc(n); }
          void operator delete(void *ptr) { ::free(ptr); }
      };
    
     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; }
      };
    
    • 关联对象并不是存储在被关联对象本身内存中
    • 关联对象存储在全局的统一的一个AssociationsManager中
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) {
    _object_set_associative_reference(object, (void *)key, value, policy);
}

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());
        // 用被关联对象作为Key
        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()) { // 如果mannager中没有设置被关联对象,则创建一个ObjectAssociationMap(哈希表),用于存储当前关联对象中所有的关联属性
                // secondary table exists
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    // 如果不存在当前Key,则添加
                    old_association = j->second;
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    // 如果存在当前key,则直接替换值
                    (*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);
}
关联对象的实现逻辑

你可能感兴趣的:(Objective-C 使用关联对象给Category添加属性)