According to this blog entry by Erica Sadun (whose credits go to Gwynne Raskind ), there is.
objc_getAssociatedObject and objc_getAssociatedObject require a key to store the object. Such a key must be a constant void pointer. Therefore, in the end, we only need a fixed address, which remains constant over time.
It turns out that the @selector implementation provides only what we need, since it uses fixed addresses.
Therefore, we can simply get rid of the key declaration and simply use our property selection address.
So, if you bind at runtime a property like
@property (nonatomic, retain) id anAssociatedObject;
we can provide dynamic implementations for our getter / setter that look like
- (void)setAnAssociatedObject:(id)newAssociatedObject { objc_setAssociatedObject(self, @selector(anAssociatedObject), newAssociatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (id)anAssociatedObject { return objc_getAssociatedObject(self, @selector(anAssociatedObject)); }
Very neat and definitely cleaner than defining an additional static variable key for each related object.
Is it safe?
Since it depends on the implementation, the legitimate question is: will it break easily? Citing Blog Entries
Apple may have to implement a completely new ABI for this to happen.
If we take these words as true, then they will be reasonably safe.
Gabriele Petronella Apr 15 '13 at 17:12 2013-04-15 17:12
source share