runtime添加属性

  运行期不能对类对象添加ivar,因为在编译期类的内存大小布局已经确定,在运行期不能修改类对象的内存空间,所以不能在运行期为对象添加ivar,比如不能在category中添加ivar,而category是运行期技术,但可以添加方法,因为类对象内的方法列表是指针,添加方法改变的是指针指向的方法列表,没有改变指针本身,不会改变类对象内存大小,所以category可以添加方法。
  有一点需要说明虽然category添加属性,但不会为这个属性自动添加ivar,只会生成settergetter方法的声明。
  所以添加属性的方法只能用objc_setAssociatedObject方式,下面重点讲述objc_setAssociatedObjectobjc_getAssociatedObject实现原理。
先看看objc_setAssociatedObject方法参数说明。

/** 
 * Sets an associated value for a given object using a given key and association policy.
 * 
 * @param object The source object for the association.
 * @param key The key for the association.
 * @param value The value to associate with the key key for object. Pass nil to clear an existing association.
 * @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
 * 
 * @see objc_setAssociatedObject
 * @see objc_removeAssociatedObjects
 */

这里要讲的是key这个参数其实是个指针值,只要保证指针值不一样就行,就算指针指向的对象值相等也没关系,有一种很优雅的写法:

objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

_cmd代表当前方法的SEL,相当于这么写@selector(currentMethod)SEL其实就是个指针,而且能保证唯一。
现在看一下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,往下看吧:

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

AssociationsManager manager是个c++对象,维护一个全局唯一单例hashmap,并且在构造函数加锁和析构函数解锁保证hashmap操作时的安全性,全局hashmap先根据当前object(key:DISGUISE(object))查找ObjectAssociationMapObjectAssociationMap存放的是ObjcAssociation对象,其实是对要存放的valuepolicy的简单封装,可以看下ObjcAssociation的定义;

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

哎,也是class

所以全局hashmap是个二维的map,ObjectAssociationMap如果没找到创建一个新的ObjectAssociationMap然后将new_value添加到map里,找到了ObjectAssociationMap再根据参数key找旧值,找到了更新旧值为新的值,没找到将new_value添加到map里。

整个查找过程是个两层的遍历。
看懂这块代码就明白:
通过objc_setAssociatedObject添加属性实际上是系统维护了一个全局的二维map,将对象与要添加的属性进行map的键值绑定。

_policy的作用在于是否需要在方法开始retain value,如果是retain policy则需要retain objc_retain(value)如果是copy则调用value的copy方法((id(*)(id, SEL))objc_msgSend)(value, SEL_copy);并且需要在方法结束时Relase,看下面的方法

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

看完objc_setAssociatedObject就知道objc_getAssociatedObject是怎么实现的了,不多说了。

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

最后在说一个小问题代码中 disguised_ptr_t disguised_object = DISGUISE(object)disguised_object作为全局map的key值,并不是吧object作为key值,disguised_object是怎么得来的需要看下代码DISGUISE方法实现

    inline disguised_ptr_t DISGUISE(id value) { return ~uintptr_t(value); }

哦很简单,object是个指针地址,把它强转成uintptr_t(实际上是long类型)然后进行取反操作。

你可能感兴趣的:(runtime添加属性)