Q:

associatedValueForKey, unrecognized key

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).

A:

If there is no association in place, objc_getAssociatedObject will return nil.
When you associate an object, it will use the semantics supplied in the last argument.  For example, OBJC_ASSOCIATION_RETAIN will 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:
objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN);

value would be retained until the association was broken.  The association would be broken when self deallocs or when the association is changed with another objc_setAssociatedObject.

