1. 程式人生 > >AssociatedObject關聯對象原理實現

AssociatedObject關聯對象原理實現

增加 引用 -c 周期 sha switch 實現 避免 復雜

介紹

關聯對象(AssociatedObject)是Objective-C 2.0運行時的一個特性,允許開發者對已經存在的類在擴展中添加自定義的屬性。在實際生產過程中,比較常用的方式是給分類(Category)添加成員變量。

例子

#import <objc/runtime.h>

@interface NSObject (AssociatedObject)

@property (nonatomic, strong) id property;

@end

@implementation NSObject (AssociatedObject)
@dynamic property;

- (id)property {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setProperty:(NSString *)property {
    objc_setAssociatedObject(self, @selector(property), property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

通過實現代碼可以稍微分析下,objc_getAssociatedObject 拿著不變的指針地址(示例傳入selector作為參數,實際是void*),從實例中獲取需要的對象。objc_setAssociatedObject 根據傳入的參數協議,保存指定的對象。

參數協議

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object. The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied. The association is made atomically. */
};

其實這五個協議就是我們平時定義屬性時使用的,需要註意的是,雖然蘋果在註釋中說 OBJC_ASSOCIATION_ASSIGN 相當於一個 weak reference,但其實等於 assign/unsafe_unretained

對於與weak的區別不在本文討論範圍內,淺顯的區別在於變量釋放後,weak 會把引用置空,unsafe_unretained會保留內存地址,一旦獲取可能會野指針閃退。

總結

我們知道,如果類要添加變量,只有在objc_allocateClassPairobjc_registerClassPair之間addIvar。等類註冊後,變量結構就不允許再被改變,這是為了防止兩個相同類的實例擁有不同變量導致運行困惑。

那麽在runtime時給實例添加變量,又不改變類內部變量結構,關聯對象就是一個比較好的做法。


關聯對象的實現

外部方法

//Sets an associated value for a given object using a given key and association policy.
void objc_setAssociatedObject(id object, const void * key, id value, objc_AssociationPolicy policy);

//Returns the value associated with a given object for a given key.
id objc_getAssociatedObject(id object, const void * key);

//Removes all associations for a given object.
void objc_removeAssociatedObjects(id object);

相比剛剛例子中的用法,多了一個objc_removeAssociatedObjects,那麽可不可以用這個方法來刪除不用的關聯對象呢?

蘋果的文檔中解釋說這個方法主要用來還原對象到類初始的狀態,會移除所有的關聯,包括其他模塊添加的,因此應該用 objc_setAssociatedObject(..,nil,..) 的方式去卸載。


Setter實現

objc_setAssociatedObject實際調用的是_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);
}

內存管理

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

static void releaseValue(id value, uintptr_t policy) {
    if (policy & OBJC_ASSOCIATION_SETTER_RETAIN) {
        return objc_release(value);
    }
}

ObjcAssociation old_association(0, nil);
id new_value = value ? acquireValue(value, policy) : nil;
{
    old_association = ...
}
if (old_association.hasValue()) ReleaseValue()(old_association);

我們摘出與對象內存相關的代碼仔細分析下,首先把新傳入的對象,根據協議進行retain/copy,在賦值的過程中獲取舊值,在方法結束前release


賦值

AssociationsManager manager;
AssociationsHashMap &associations(manager.associations());
disguised_ptr_t disguised_object = DISGUISE(object);
if (new_value) {
    //需要賦值
    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()) {
            //找到了這個key的關聯對象
            old_association = j->second;
            j->second = ObjcAssociation(policy, new_value);
        } else {
            //沒找到,新增一個關聯
            (*refs)[key] = ObjcAssociation(policy, new_value);
        }
    } else {
        //沒找到,創建一個新的關聯表
        ObjectAssociationMap *refs = new ObjectAssociationMap;
        associations[disguised_object] = refs;
        (*refs)[key] = ObjcAssociation(policy, new_value);
        object->setHasAssociatedObjects();
    }
}

先了解一下AssociationsManagerAssociationsHashMap

class AssociationsManager {
    static AssociationsHashMap *_map;
public:
    AssociationsHashMap &associations() {
        if (_map == NULL)
            _map = new AssociationsHashMap();
        return *_map;
    }
};

class AssociationsHashMap : public unordered_map<disguised_ptr_t, ObjectAssociationMap *, DisguisedPointerHash, DisguisedPointerEqual, AssociationsHashMapAllocator>;

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

AssociationsManager通過一個以指針地址為主鍵,值為關聯表的哈希表,來管理應用內所有的關聯對象。

首先以對象的指針地址去尋找關聯表,再通過指定的鍵值查找關聯關系,從而獲取關聯對象。

刪除

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

和修改方法類似,找到關聯關系後,執行哈希表的erase方法刪除。


Getter實現

objc_getAssociatedObject實際調用的是_object_get_associative_reference

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

查找哈希表的方法和Setter一樣,區別在於如果策略中需要retain和autorelease的話,都需要處理。那麽是怎麽約定這些策略呢?

enum { 
    OBJC_ASSOCIATION_SETTER_ASSIGN      = 0,
    OBJC_ASSOCIATION_SETTER_RETAIN      = 1,
    OBJC_ASSOCIATION_SETTER_COPY        = 3,            // NOTE:  both bits are set, so we can simply test 1 bit in releaseValue below.
    OBJC_ASSOCIATION_GETTER_READ        = (0 << 8), 
    OBJC_ASSOCIATION_GETTER_RETAIN      = (1 << 8), 
    OBJC_ASSOCIATION_GETTER_AUTORELEASE = (2 << 8)
}; 

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
    OBJC_ASSOCIATION_RETAIN = 01401, 
    OBJC_ASSOCIATION_COPY = 01403
};

OBJC_ASSOCIATION_RETAIN = 01401,其中01401開頭是0,所以是八進制數字,翻譯為二進制就是0000 0011 0000 0001,取位判斷就是OBJC_ASSOCIATION_SETTER_RETAIN OBJC_ASSOCIATION_GETTER_RETAIN OBJC_ASSOCIATION_GETTER_AUTORELEASE

在保存的時候,需要retain,在獲取的時候,需要先retain增加引用計數,再執行autorelease等待釋放,從而實現原子性。

Remove實現

objc_removeAssociatedObjects會判斷對象是否存在關聯,然後再執行_object_set_associative_reference

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

實現方式也可以看出為什麽在介紹裏不推薦使用,因為會遍歷所有的關聯對象,並且全部釋放,可能會造成別的模塊功能缺陷。

判斷關聯對象

比較有意思的是判斷對象是否有關聯對象的實現。

inline bool objc_object::hasAssociatedObjects()
{
    if (isTaggedPointer()) return true;
    if (isa.nonpointer) return isa.has_assoc;
    return true;
}
inline void objc_object::setHasAssociatedObjects()
{
    if (isTaggedPointer()) return;

 retry:
    isa_t oldisa = LoadExclusive(&isa.bits);
    isa_t newisa = oldisa;
    if (!newisa.nonpointer  ||  newisa.has_assoc) {
        ClearExclusive(&isa.bits);
        return;
    }
    newisa.has_assoc = true;
    if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
}

默認返回的結果都是true,只有在64位系統下,才保存一個標記位。這麽處理我推測是為了加快釋放周期速度,在析構對象時,會根據這個方法判斷是否需要釋放關聯對象。試想如果每次都查詢哈希表,執行效率必定會降低,不如都先通過,之後再做處理。

關於nonpointer不在本文介紹範圍內,簡單描述為在64位系統下,指針地址保存不僅僅為內存地址,還存有其他標記信息,包括本文涉及的has_assoc。

taggedPointer是一種優化策略,把簡單的數字或字符串信息直接保存在指針地址中,從而不申請額外內存加快運行效率。

總結

關聯對象的實現不復雜,保存的方式為一個全局的哈希表,存取都通過查詢表找到關聯來執行。哈希表的特點就是犧牲空間換取時間,所以執行速度也可以保證。


問答

關聯對象有什麽應用?

關聯對象可以在運行時給指定對象綁定一個有生命周期的變量。

1.由於不改變原類的實現,所以可以給原生類或者是打包的庫進行擴展,一般配合Category實現完整的功能。

2.ObjC類定義的變量,由於runtime的特性,都會暴露到外部,使用關聯對象可以隱藏關鍵變量,保證安全。

3.可以用於KVO,使用關聯對象作為觀察者,可以避免觀察自身導致循環。

系統如何管理關聯對象?

系統通過管理一個全局哈希表,通過對象指針地址和傳遞的固定參數地址來獲取關聯對象。根據setter傳入的參數協議,來管理對象的生命周期。

其被釋放的時候需要手動將其指針置空麽?

當對象被釋放時,如果設置的協議是OBJC_ASSOCIATION_ASSIGN,那麽他的關聯對象不會減少引用計數,其他的協議都會減少從而釋放關聯對象。

unsafe_unretain一般認為外部有對象控制,所以對象不用處理,因此不管什麽協議,對象釋放時都無需手動講關聯對象置空。

AssociatedObject關聯對象原理實現