objective-c - 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
解决方案
首先,你需要model
在你的MediatorController
@interface MediatorController : NSObject
@property (strong, nonatomic) Model* model; //<-- Here
- (int)addOne;
- (int)subtractOne;
- (void)setValue:(int)value;
- (int)value;
@end
然后,你需要一个init
方法——现在,你正试图model =
在实现的顶层编写你的方法,这不起作用——它需要在一个方法中。
最后,不要调用add
on 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
您最终会收到一些编译器警告,因为您还没有实现其余的方法(subtractOne
、setValue
等),但这会让您开始。
推荐阅读
- powershell - 禁止 Visual Studio Code 中的特定警告?
- html - 当没有空间时,每列彼此相邻而不是下方?
- angular - 重定向后AWS Cognito错误的发行者
- reactjs - Typescript:如何在 React 类组件中继承泛型状态类型?
- ios - 药丸形 UIButton 的摆动动画的奇怪行为
- javascript - 如何解释 Chrome 内存分析结果、内存分配时间线 - GSAP Tween 内存泄漏
- typescript - 在打字稿中省略对象属性
- node.js - 前端服务器无法连接到 Github Actions 中的后端
- sql - SQL 在 SQL Server 中使用声明创建视图
- c++ - 类内的c ++模板参数