iOS子类化自定义类

Sla*_*jic 6 inheritance subclass objective-c ios

我在编写关于类继承的想法时遇到了麻烦.我想在应用程序中创建一个类似界面的仪表板,我可能在该仪表板视图上有10个小部件/小程序.所有这些小面板/小部件将具有基本相同的外观,顶部的标题,顶部的边框,按钮行和图形.假设我创建了一个名为'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
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

现在让我们说我创建了一个名为CustomDashlet.h的子类:

@interface CustomDashlet : Dashlet
@property (nonatomic, strong) NSString* test;
-(void)testMethod;
-(void)someDummyMethod;
@end
Run Code Online (Sandbox Code Playgroud)

和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;
}
Run Code Online (Sandbox Code Playgroud)

这种,有点工作,但我需要覆盖超类中声明的一些方法,甚至添加我自己的一些方法.每当我尝试在CustomDashlet.m中做这样的事情

[self someDummyMethod]甚至[self testMethod]我得到这样的异常错误:

NSInvalidArgumentException', reason: '-[Dashlet testMethod]: unrecognized selector sent to instance 
Run Code Online (Sandbox Code Playgroud)

我甚至这样做了吗?我错过了什么?我应该以其他方式做这项工作吗?如果有人有任何建议,请随时分享您的想法,谢谢您的帮助.

Mar*_*n R 5

问题是

SalesDashlet *sales = [[SalesDashlet alloc] initWithParams:nil];
Run Code Online (Sandbox Code Playgroud)

不会像预期的那样返回SalesDashlet实例,而是返回Dashlet实例.这是发生的事情:

  • [SalesDashlet alloc]分配一个实例SalesDashlet.
  • initWithParams:使用此实例调用子类实现,并调用self = [super initWithParams:parameters].
  • initWithParams 丢弃 的超类实现,self并 使用从Nib文件加载的新实例覆盖它.这是一个例子Dashlet.
  • 返回此新实例.

因此SalesDashlet *sales"仅"是a Dashlet,并且在其上调用任何子类方法会抛出"未知选择器"异常.

您无法更改Nib文件中加载的对象类型.您可以创建包含SalesDashlet对象的第二个Nib文件.如果子类的主要目的是添加其他方法,那么最简单的解决方案是在类的类别中添加这些方法Dashlet.