AssociatedObject關聯物件原理實現

VanchChen發表於2019-02-27

介紹

關聯物件(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一般認為外部有物件控制,所以物件不用處理,因此不管什麼協議,物件釋放時都無需手動講關聯物件置空。

相關文章