I’m looking into ways to add a property (an integer in this case) to all UIView
instances, whether they are subclassed or not. Is using objc_setAssociated
Associated objects come in handy whenever you want to fake an ivar on a class. They are very versatile as you can associate any object to that class.
That said, you should use it wisely and only for minor things where subclassing feels cumbersome.
However, if your only requirement is to add an integer to all UIView
instances, tag
is the way to go. It's already there and ready for you to use, so there's no need for involving run-time patching of UIView
.
If you instead want to tag your UIView
with something more than an integer, like a generic object, you can define a category like follows.
@interface UIView (Tagging)
@property (nonatomic, strong) id customTag;
@end
#import
@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 of using a property's selector as key, has recently been proposed by Erica Sadun in this blog post.