關聯對象(AssociatedObject)是Objective-C 2.0運行時的一個特性,容許開發者對已經存在的類在擴展中添加自定義的屬性。在實際生產過程當中,比較經常使用的方式是給分類(Category)添加成員變量。c++
#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
。markdown
對於與weak
的區別不在本文討論範圍內,淺顯的區別在於變量釋放後,weak
會把引用置空,unsafe_unretained
會保留內存地址,一旦獲取可能會野指針閃退。app
咱們知道,若是類要添加變量,只有在objc_allocateClassPair
與objc_registerClassPair
之間addIvar
。等類註冊後,變量結構就不容許再被改變,這是爲了防止兩個相同類的實例擁有不一樣變量致使運行困惑。ide
那麼在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
,那麼可不能夠用這個方法來刪除不用的關聯對象呢?ui
蘋果的文檔中解釋說這個方法主要用來還原對象到類初始的狀態,會移除全部的關聯,包括其餘模塊添加的,所以應該用 objc_setAssociatedObject(..,nil,..)
的方式去卸載。atom
objc_setAssociatedObject
實際調用的是_object_set_associative_reference
spa
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(); } } 複製代碼
先了解一下AssociationsManager
與AssociationsHashMap
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
方法刪除。
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
等待釋放,從而實現原子性。
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
通常認爲外部有對象控制,因此對象不用處理,所以無論什麼協議,對象釋放時都無需手動講關聯對象置空。