方法定义:
/*** Sets an associated value for a given object using a given key and association policy.** @param object 要添加关联属性到哪个关联对象上* @param key 标识符,设值和取值一样就可以* @param value 标识符对应的值,传 nil 会清空已存在的association* @param policy 关联对象的策略*/OBJC_EXPORT voidobjc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,id _Nullable value, objc_AssociationPolicy policy)OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);/*** Returns the value associated with a given object for a given key.*/OBJC_EXPORT id _Nullableobjc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);/*** Removes all associations for a given object.*/OBJC_EXPORT voidobjc_removeAssociatedObjects(id _Nonnull object)OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
使用实例:
关联对象的内部存储结构:
关联对象类型源码定义
1.AssociationsManager 源码定义
class AssociationsManager {using Storage = ExplicitInitDenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap>;static Storage _mapStorage; // 静态变量,全局唯一的public:AssociationsManager() { AssociationsManagerLock.lock(); }~AssociationsManager() { AssociationsManagerLock.unlock(); }AssociationsHashMap &get() {return _mapStorage.get();}static void init() {_mapStorage.init();}};
2.ObjcAssociationMap & AssociationsHashMap 源码定义:
typedef DenseMap<const void *, ObjcAssociation> ObjectAssociationMap;typedef DenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap> AssociationsHashMap;
3.ObjcAssociation 源码定义:
class ObjcAssociation {uintptr_t _policy;id _value;...}
关联对象读写流程分析
1. 赋值过程
void_object_set_associative_reference(id object, const void *key, id value, uintptr_t policy){// This code used to work when nil was passed for object and key. Some code// probably relies on that to not crash. Check and handle it explicitly.// rdar://problem/44094390if (!object && !value) return;if (object->getIsa()->forbidsAssociatedObjects())_objc_fatal("objc_setAssociatedObject called on instance (%p) of class %s which does not allow associated objects", object, object_getClassName(object));DisguisedPtr<objc_object> disguised{(objc_object *)object};ObjcAssociation association{policy, value};// retain the new value (if any) outside the lock.association.acquireValue();{AssociationsManager manager;AssociationsHashMap &associations(manager.get());if (value) { // 有值auto refs_result = associations.try_emplace(disguised, ObjectAssociationMap{});if (refs_result.second) {/* it's the first association we make */object->setHasAssociatedObjects();}/* establish or replace the association */auto &refs = refs_result.first->second;auto result = refs.try_emplace(key, std::move(association));if (!result.second) {association.swap(result.first->second);}} else { // 赋空值, 移除 HashMap 中该类的auto refs_it = associations.find(disguised);if (refs_it != associations.end()) {auto &refs = refs_it->second;auto it = refs.find(key);if (it != refs.end()) {association.swap(it->second);refs.erase(it);if (refs.size() == 0) {associations.erase(refs_it);}}}}}// release the old value (outside of the lock).association.releaseHeldValue();}
2. 取值过程
id_object_get_associative_reference(id object, const void *key){ObjcAssociation association{};//创建空的关联对象{AssociationsManager manager;//创建一个AssociationsManager管理类AssociationsHashMap &associations(manager.get());//获取全局唯一的静态哈希mapAssociationsHashMap::iterator i = associations.find((objc_object *)object);//找到迭代器,即获取bucketsif (i != associations.end()) {//如果这个迭代查询器不是最后一个 获取ObjectAssociationMap &refs = i->second; //找到ObjectAssociationMap的迭代查询器获取一个经过属性修饰符修饰的valueObjectAssociationMap::iterator j = refs.find(key);//根据key查找ObjectAssociationMap,即获取bucketif (j != refs.end()) {association = j->second;//获取ObjcAssociationassociation.retainReturnedValue();}}}return association.autoreleaseReturnedValue();//返回value}


