Any gotchas with objc_setAssociatedObject and objc_getAssociatedObject?

I am looking at ways to add a property (integer in this case) to all instances of UIView , regardless of whether they are a subclass or not. Does objc_setAssociatedObject() and objc_getAssociatedObject() in the category use a suitable, Apple-approved way to do this?

I have heard some concerns that this constitutes a β€œrun-time hack” and may lead to problems that are difficult to track and debug. Has anyone else seen this problem? Is there a better way to add an integer property to all instances of a UIView without a subclass?

Update: I can’t use tag because it needs to be used in a code base that already uses tag for other purposes. Believe me, if I could use a tag for this, I would!

+6
ios objective-c objective-c-runtime
Apr 15 '13 at 16:05
source share
2 answers

Linked objects come in handy whenever you want to fake ivar in a class. They are very versatile since you can associate any object with this class.

However, you should use it wisely and only for minor things when subclasses seem cumbersome.

However, if your only requirement is to add an integer to all instances of UIView , tag is the way to go. This is already there and is ready for you to use, so there is no need to include corrections at runtime of the UIView .

If you want to tag your UIView with something larger than an integer, such as a shared object, you can define a category as shown below.

UIView + Tagging.h

 @interface UIView (Tagging) @property (nonatomic, strong) id customTag; @end 

UIView + Tagging.m

 #import <objc/runtime.h> @implementation UIView (Tagging) @dynamic customTag; - (id)customTag { return objc_getAssociatedObject(self, @selector(customTag)); } - (void)setCustomTag:(id)aCustomTag { objc_setAssociatedObject(self, @selector(customTag), aCustomTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end 

The trick using the property selector as a key was recently proposed by Erica Sadun in this post.

+8
Apr 15 '13 at 16:13
source share

Use tag . This is what it was intended for.

-2
Apr 15 '13 at 16:07
source share



All Articles