
假设我创建了一个名为’Dashlet’的UI视图的子类,其中包含属性和出口,并创建具有适当布局和连接出口等的XIB文件.
现在我想创建几个“Dashlet”视图的子类,它只会以不同的方式处理数据,并绘制不同的图形.我当前的代码看起来像这样:
Dashlet.h
@interface Dashlet : UIVIEw{@private UILabel *Title; UIVIEw *controls; UIVIEw *graph; }@property (weak,nonatomic) IBOutlet UILabel *Title;@property (weak,nonatomic) IBOutlet UIVIEw *controls;@property (weak,nonatomic) IBOutlet UIVIEw *graph;-(Dashlet*)initWithParams:(NSMutableDictionary *)params;-(voID)someDummyMethod;@end 在Dashlet.m
- (ID) init { self = [super init]; //Basic empty init... return self;}- (ID)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { } return self;}-(ID)initWithParams:(NSMutableDictionary *)params{ self = [super init]; if (self) { self = [[[NSBundle mainBundle] loadNibnamed:@"Dashlet" owner:nil options:nil] lastObject]; //some init code } return self;} 现在让我们说我创建了一个名为CustomDashlet.h的子类:
@interface CustomDashlet : Dashlet@property (nonatomic,strong) Nsstring* test;-(voID)testMethod;-(voID)someDummyMethod;@end
和CustomDashlet.m
-(ID)init{ return self;}- (ID)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { } return self;}-(ID)initWithParams:(NSMutableDictionary *)parameters{ self = [super initWithParams:parameters]; if (self) { //do some stuff } return self;} 这种,有点工作,但我需要覆盖超类中声明的一些方法,甚至添加我自己的一些方法.每当我尝试在CustomDashlet.m中做这样的事情
[self someDummyMethod]甚至[self testMethod]我得到一个像这样的异常错误:
NSinvalidargumentexception',reason: '-[Dashlet testMethod]: unrecognized selector sent to instance
我甚至这样做了吗?我错过了什么?我应该以其他方式做这项工作吗?如果有人有任何建议,请随时分享您的想法,谢谢您的帮助.
@H_403_30@解决方法 问题是SalesDashlet *sales = [[SalesDashlet alloc] initWithParams:nil];
不会按预期返回SalesDashlet实例,而是返回Dashlet实例.
这是发生的事情:
> [SalesDashlet alloc]分配SalesDashlet的实例.
>使用此实例调用initWithParams:的子类实现,
并调用self = [super initWithParams:parameters].
> initWithParams的超类实现丢弃self和
用从Nib文件加载的新实例覆盖它.这是一个实例
达什莱特
>返回此新实例.
因此SalesDashlet * sales“仅”是Dashlet,并且调用任何子类
它上面的方法抛出一个“未知选择器”异常.
您无法更改Nib文件中加载的对象类型.你可以创建第二个包含SalesDashlet对象的Nib文件.如果子类的主要目的是要添加其他方法,最简单的解决方案是添加这些方法在Dashlet类的类别中.
总结以上是内存溢出为你收集整理的iOS子类化自定义类全部内容,希望文章能够帮你解决iOS子类化自定义类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)