Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending existing classes by adding instance variables

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.

like image 623
OgreSwamp Avatar asked Dec 07 '25 04:12

OgreSwamp


2 Answers

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.

like image 122
bbum Avatar answered Dec 08 '25 16:12

bbum


You cannot add ivars using categories.

like image 35
FreeAsInBeer Avatar answered Dec 08 '25 16:12

FreeAsInBeer