preface

In iOS, we add attributes, member variables, and runtime Associated APIS, but we do not understand the principle. Here is the essence and principle of Associated objects.

1. The nature of the associated object

  • The associated object is not stored in the memory of the associated object itself, and there is no memory relationship with the original object. The associated object is stored in a unified global AssociationsManager.

  • Setting the associated object to nil is equivalent to removing the associated object.

2. The principle of association

  • The system uses the AssociationsManager to manage multiple hash maps, and uses object_set_associative to set corresponding keys and values to store them in the hash map. In the extraction process, the corresponding value is extracted through the corresponding key.
  • If you use a dictionary, you can also implement the function of the corresponding class, so that the classification can also have attributes.

3. Specific principles

First of all, the system has a global AssociationsManager, which contains an AssociationsHashMap hash table. The key in the hash table is the memory address of the object, and the value is the ObjectAssociationMap, which is also a hash table. Where key is the key set by the associated object, value is the Object Society, which stores the value set by the associated object and the memory management policy.

Void objc_setAssociatedObject(ID object, const void * key, ID value, objc_AssociationPolicy policy) First, the AssociationsHashMap is obtained through the AssociationsManager. Then, the Memory address of the object is used as the key to retrieve the AssociationsHashMap. Objcassociety (policy, new_value) is generated by key and policy. The new value is stored in ObjectAssociationMap. If the new value is not nil and the memory management policy is RETAIN, the new value is retained once, if the new value is nil, the old value is removed, and if the old value is not empty and the memory management policy is RETAIN, the old value is released once

4. Associated objects provide the following apis

5. Common uses of key

6. Principle of associated objects