How to free objects linked via objc_setAssociatedObject?

If I use a category that uses objc_setAssociatedObject to add pseudo-properties to an object, how can I make sure they are released correctly? Should I release them manually in dealloc ?

+7
source share
2 answers

The assignment you assign determines the memory management method for the type. If you choose to save or copy the object, it will be released when the class instance that you add the linked link is released. This makes save and copy operations preferred for Objective-C classes. Assignment is also useful to avoid save loops until you link to nil when you're done with the object.

Constants

OBJC_ASSOCIATION_ASSIGN Indicates a weak reference to the associated object.

OBJC_ASSOCIATION_RETAIN_NONATOMIC Indicates a strong reference to a related object, and that the association is not atomic.

OBJC_ASSOCIATION_COPY_NONATOMIC Indicates that the associated object is being copied and that the association has not been created atomically.

OBJC_ASSOCIATION_RETAIN Defines a strong reference to a related object, and that the association is atomic.

OBJC_ASSOCIATION_COPY Indicates that the associated object is being copied and that the association is atomic.

+16
source

Although you answered your own question, however, since you did not include the text of the document itself, and the page you are linked to is no longer available, here is for the convenience of others:

From Apple Objective-C Runtime Reference

void objc_removeAssociatedObjects(id object)

Deletes all associations for this object.

The main purpose of this function is to facilitate the return of the object to its "pristine state." You should not use this function to remove associations from objects altogether, as it also removes associations that other clients might add to the object. Normally you should use objc_setAssociatedObject with a null value to clear the association.

+2
source

All Articles