方法定义:

  1. /**
  2. * Sets an associated value for a given object using a given key and association policy.
  3. *
  4. * @param object 要添加关联属性到哪个关联对象上
  5. * @param key 标识符,设值和取值一样就可以
  6. * @param value 标识符对应的值,传 nil 会清空已存在的association
  7. * @param policy 关联对象的策略
  8. */
  9. OBJC_EXPORT void
  10. objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
  11. id _Nullable value, objc_AssociationPolicy policy)
  12. OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
  13. /**
  14. * Returns the value associated with a given object for a given key.
  15. */
  16. OBJC_EXPORT id _Nullable
  17. objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
  18. OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
  19. /**
  20. * Removes all associations for a given object.
  21. */
  22. OBJC_EXPORT void
  23. objc_removeAssociatedObjects(id _Nonnull object)
  24. OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);

使用实例:
image.png

关联对象的内部存储结构:

image.png
简单理解关系结构就是这样:
image.png

关联对象类型源码定义

1.AssociationsManager 源码定义

  1. class AssociationsManager {
  2. using Storage = ExplicitInitDenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap>;
  3. static Storage _mapStorage; // 静态变量,全局唯一的
  4. public:
  5. AssociationsManager() { AssociationsManagerLock.lock(); }
  6. ~AssociationsManager() { AssociationsManagerLock.unlock(); }
  7. AssociationsHashMap &get() {
  8. return _mapStorage.get();
  9. }
  10. static void init() {
  11. _mapStorage.init();
  12. }
  13. };

2.ObjcAssociationMap & AssociationsHashMap 源码定义:

  1. typedef DenseMap<const void *, ObjcAssociation> ObjectAssociationMap;
  2. typedef DenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap> AssociationsHashMap;

3.ObjcAssociation 源码定义:

  1. class ObjcAssociation {
  2. uintptr_t _policy;
  3. id _value;
  4. ...
  5. }

关联对象读写流程分析

1. 赋值过程

  1. void
  2. _object_set_associative_reference(id object, const void *key, id value, uintptr_t policy)
  3. {
  4. // This code used to work when nil was passed for object and key. Some code
  5. // probably relies on that to not crash. Check and handle it explicitly.
  6. // rdar://problem/44094390
  7. if (!object && !value) return;
  8. if (object->getIsa()->forbidsAssociatedObjects())
  9. _objc_fatal("objc_setAssociatedObject called on instance (%p) of class %s which does not allow associated objects", object, object_getClassName(object));
  10. DisguisedPtr<objc_object> disguised{(objc_object *)object};
  11. ObjcAssociation association{policy, value};
  12. // retain the new value (if any) outside the lock.
  13. association.acquireValue();
  14. {
  15. AssociationsManager manager;
  16. AssociationsHashMap &associations(manager.get());
  17. if (value) { // 有值
  18. auto refs_result = associations.try_emplace(disguised, ObjectAssociationMap{});
  19. if (refs_result.second) {
  20. /* it's the first association we make */
  21. object->setHasAssociatedObjects();
  22. }
  23. /* establish or replace the association */
  24. auto &refs = refs_result.first->second;
  25. auto result = refs.try_emplace(key, std::move(association));
  26. if (!result.second) {
  27. association.swap(result.first->second);
  28. }
  29. } else { // 赋空值, 移除 HashMap 中该类的
  30. auto refs_it = associations.find(disguised);
  31. if (refs_it != associations.end()) {
  32. auto &refs = refs_it->second;
  33. auto it = refs.find(key);
  34. if (it != refs.end()) {
  35. association.swap(it->second);
  36. refs.erase(it);
  37. if (refs.size() == 0) {
  38. associations.erase(refs_it);
  39. }
  40. }
  41. }
  42. }
  43. }
  44. // release the old value (outside of the lock).
  45. association.releaseHeldValue();
  46. }

2. 取值过程

  1. id
  2. _object_get_associative_reference(id object, const void *key)
  3. {
  4. ObjcAssociation association{};//创建空的关联对象
  5. {
  6. AssociationsManager manager;//创建一个AssociationsManager管理类
  7. AssociationsHashMap &associations(manager.get());//获取全局唯一的静态哈希map
  8. AssociationsHashMap::iterator i = associations.find((objc_object *)object);//找到迭代器,即获取buckets
  9. if (i != associations.end()) {//如果这个迭代查询器不是最后一个 获取
  10. ObjectAssociationMap &refs = i->second; //找到ObjectAssociationMap的迭代查询器获取一个经过属性修饰符修饰的value
  11. ObjectAssociationMap::iterator j = refs.find(key);//根据key查找ObjectAssociationMap,即获取bucket
  12. if (j != refs.end()) {
  13. association = j->second;//获取ObjcAssociation
  14. association.retainReturnedValue();
  15. }
  16. }
  17. }
  18. return association.autoreleaseReturnedValue();//返回value
  19. }

image.png