我正在尝试将UIColor子类化,我似乎无法弄清楚什么是错的.
在我的PColor.h中
#import <Foundation/Foundation.h> @interface PColor : UIColor { BOOL isAvailable; int colorId; } @property (nonatomic,assign) BOOL isAvailable; @property (nonatomic,assign) int colorId; @end
……在我的PColor.m中
#import "PColor.h" @implementation PColor @synthesize isAvailable; @synthesize colorId; @end
在实例化PColor对象时,我得到:
//warning: incompatible Objective-C types initializing 'struct UIColor *',expected 'struct PColor *' PColor *pcolor = [[PColor alloc] initWithHue:1 saturation:0 brightness:0 alpha:1];
我错过了什么吗?提前致谢.
解决方法
UIColor是一个类集群,在类别中使用
associative references来添加属性! UIColor上的所有自定义init方法都返回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
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];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。