objective-c – 不能子类化UIColor?
发布时间:2020-12-16 10:18:55 所属栏目:百科 来源:网络整理
导读:我正在尝试将UIColor子类化,我似乎无法弄清楚什么是错的. 在我的PColor.h中 #import Foundation/Foundation.h@interface PColor : UIColor { BOOL isAvailable; int colorId;}@property (nonatomic,assign) BOOL isAvailable;@property (nonatomic,assign) i
我正在尝试将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: %dnIs Availabled: %@",NSStringFromClass([pcolor class]),pcolor.pColorId,pcolor.pIsAvailable ? @"YES" : @"NO"); [pcolor release]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – MEF的DirectoryCatalog如何工作?
- 直播回顾 | 数字赋能 加速保险行业数字化转型
- 模版:XxxAction-validation.xml
- c# – 在asp.net MVC 4 webapp中存储用户上传文件的位置?
- 《深入react技术栈》学习笔记(一)初入React世界
- PostgreSQL选择多个OR语句的位置
- 用VS编译出不依赖VC运行库的可独立运行的程序
- Flash Paper 仿百度文库的功能实现,也可以当作预览功能使用
- ruby-on-rails – 如何检测rails应用程序是否在Unicorn下运
- Ruby:Hash.keys和Hash.values方法返回的键/值的顺序是什么