Ogr*_*amp 2 iphone cocoa objective-c
在Objective-C中,如果我需要向UIButton添加其他方法,我可以使用Categories.是否有任何简单的方法(子类除外)添加额外的实例变量或属性(实例变量+ getter/setter).假设我想在UIButton中存储UIColor引用.
PS:这是理论问题.我已经使用子类化实现了它,但寻找"更好"的方式.
谢谢.
一种解决方案是使用关联引用; 没有像伊娃一样快,但非常有用.
即给出:
@interface UIButton (color)
@property (nonatomic, retain) UIColor *myPrefixColor;
@end
Run Code Online (Sandbox Code Playgroud)
您可以将其实现为:
@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
Run Code Online (Sandbox Code Playgroud)
的myPrefix东西,是因为你应该从来没有方法添加到现有的类没有前缀"时间的东西,从而与现有方法的碰撞的机会(你是不知道的)被最小化.