Question

I'm planning to add to iVars to a category with objc_setAssociatedObject(). However, I'm unsure on when to call objc_removeAssociatedObjects() to get rid of them.

Is there a way the category can know when the object using it has been de-allocated ?

Was it helpful?

Solution

If you set an association with

objc_setAssociatedObject(self, &key, otherObject, OBJC_ASSOCIATION_RETAIN);
// or OBJC_ASSOCIATION_RETAIN_NONATOMIC

then otherObject is automatically released when self is deallocated. (At least if you use ARC, but I think this is also correct with manual reference counting.)

So you don't have to call objc_removeAssociatedObjects() explicitly, unless you want to get rid of the added objects before the main object is deallocated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top