UIColor
是類集羣使用associative references在一個類別添加屬性! UIColor
上的所有自定義初始化方法都會返回UIColor*
而不是id
,因此您無法輕易子類UIColor
,也不應該嘗試。
的UIColor + PCOLOR.h
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@interface UIColor(PCOLOR)
//Properties prefixed to try and avoid future conflicts
@property (nonatomic, assign) BOOL pIsAvailable;
@property (nonatomic, assign) int pColorId;
@end
的UIColor + PCOLOR.h
#import "UIColor+PCOLOR.h"
@implementation UIColor(PCOLOR)
static char PCOLOR_ISAVAILABLE_KEY;
static char PCOLOR_COLORID_KEY;
@dynamic pIsAvailable, pColorId;
-(void)setPIsAvailable:(BOOL)pIsAvailable
{
objc_setAssociatedObject(self, &PCOLOR_ISAVAILABLE_KEY, [NSNumber numberWithBool:pIsAvailable], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(BOOL)pIsAvailable
{
return [(NSNumber*)objc_getAssociatedObject(self, &PCOLOR_ISAVAILABLE_KEY) boolValue];
}
-(void)setPColorId:(int)pColorId
{
objc_setAssociatedObject(self, &PCOLOR_COLORID_KEY, [NSNumber numberWithInt:pColorId], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(int)pColorId
{
return [(NSNumber*)objc_getAssociatedObject(self, &PCOLOR_COLORID_KEY) intValue];
}
@end
USAGE
UIColor *pcolor = [[UIColor alloc] initWithHue:1 saturation:0 brightness:0 alpha:1];
pcolor.pColorId = 2352;
pcolor.pIsAvailable = YES;
NSLog(@"\nClass: %@\nColor ID: %d\nIs Availabled: %@",
NSStringFromClass([pcolor class]),
pcolor.pColorId,
pcolor.pIsAvailable ? @"YES" : @"NO");
[pcolor release];
來源
2011-04-20 14:01:05
Joe
這是一個非常徹底的答案......謝謝喬。關聯參考=真棒。 – Chazbot 2011-04-22 23:05:06
不錯的答案一起來...一個dout爲什麼OBJC_ASSOCIATION_RETAIN_NONATOMIC爲Bool值OBJC_ASSOCIATION_ASSIGN足夠了......? – ShivaPrasad 2012-04-11 06:41:26
@jeeva如果你看,你只能將'objects'作爲關聯對象存儲,所以'BOOL'需要被包裝成'NSNumber',然後需要保留。 – Joe 2012-04-11 12:59:10