If I haven’t used ‘objc_setAssociatedObject’ to associate an object/key to an NSObject, and then I call ‘objc_getAssociatedObject’, is this safe?
I’ve tested it in the simulator and it doesn’t crash, but I want to be sure.
And when I make the call:
objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN);
Does the object that I associate with my NSObject get released when my NSObject is dealloc’d? (I’m using ARC).
If there is no association in place,
objc_getAssociatedObjectwill returnnil.When you associate an object, it will use the semantics supplied in the last argument. For example,
OBJC_ASSOCIATION_RETAINwill retain the object so it is not deallocated as long as the association is in place.When the object that holds the association (the first parameter to
objc_setAssociatedObject) deallocs, it will break the association. When the association is broken, the retained object will be released (if it was retained to begin with).So, for your example:
valuewould be retained until the association was broken. The association would be broken whenselfdeallocs or when the association is changed with anotherobjc_setAssociatedObject.