UIColor
is a 类簇 use 关联参考在类别中添加属性!所有自定义 init 方法UIColor
返回一个UIColor*
not an 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];