in Objective-C if I need to add additional method to UIButton I can use Categories for that. Is there any easy way (except subclassing) to add additional instance variable or property (instance variable + getter/setter). Let's say I want to store UIColor reference in UIButton.
PS: It is mor theory question. I already implemented that using subclassing but looking for "nicer" way.
Thanks.
One solution is to use associative references; not as fast as ivars, but quite useful.
I.e. given:
@interface UIButton (color)
@property (nonatomic, retain) UIColor *myPrefixColor;
@end
You could implement this as:
@implementation UIButton (color)
static const char *assocKey = "myPrefixColor associated object key";
- (void) setMyPrefixColor: (UIColor*) aColor
{
objc_setAssociatedObject(self, &assocKey, aColor, OBJC_ASSOCIATION_RETAIN);
}
- (UIColor*)myPrefixColor;
{
return objc_getAssociatedObject(self, &assocKey);
}
@end
The myPrefix stuff is because you should never add methods to existing classes without prefixing 'em with something such that the chance of a collision with an existing method (that you aren't aware of) are minimized.
You cannot add ivars using categories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With