首页 > 解决方案 > How to inherit object and initialize : Objective-C

问题描述

I created an object called Model that has some methods. I want to import Model into Mediator to use its methods there. But when I try to do this in Mediator.m I keep getting errors: Initializer element is not a compile-time constant & No known class method for selector 'add'

I'm confused at to what these error are getting at. Researching them has not made things more clear.

Model.h

@interface Model : NSObject

@property (nonatomic) NSInteger tally;
-(int) add;

@end

Model.m

 #import "Model.h"
    @interface Model ()
    
    @end
    
    @implementation Model
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tally = 0;
    }
    return self;
}

- (int)add {
    self.tally = self.tally + 1;
    return self.tally;
}


@end

Mediator.h

@interface MediatorController : NSObject
    
- (int)addOne;

@end

Mediator.m

@interface MediatorController ()


@end

@implementation MediatorController

Model *model = [[Model alloc] init];      <<<<<<< "Initializer element is not a compile-time constant"

- (int)addOne {
    return [Model add];        <<<<<< "No known class method for selector 'add"
}


@end

标签: objective-coopmethods

解决方案


首先,你需要model在你的MediatorController

@interface MediatorController : NSObject

@property (strong, nonatomic) Model* model; //<-- Here

- (int)addOne;
- (int)subtractOne;
- (void)setValue:(int)value;
- (int)value;

@end

然后,你需要一个init方法——现在,你正试图model =在实现的顶层编写你的方法,这不起作用——它需要在一个方法中。

最后,不要调用addon Model(这是类),而是调用它 on self.model,这是类的实例。

@implementation MediatorController

- (instancetype)init { //< -- Here
    if (self = [super init]) {
        self.model = [Model new];
    }
    return self;
}

- (int)addOne {
    return [self.model add];
}

@end

您最终会收到一些编译器警告,因为您还没有实现其余的方法(subtractOnesetValue等),但这会让您开始。


推荐阅读