Objective-c:无法初始化类对象

bez*_*oon 1 objective-c

我遇到一个问题,即使在向构造函数添加行后也无法初始化类对象,例如

self = [super init];
Run Code Online (Sandbox Code Playgroud)

或者

self = [[super init] alloc];
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么办。

这是具体的错误:

file:///%3Cunknown%3E: test failure: -[LinkedListTest testAdd] failed: *** +[NList<0x8e14> init]: cannot init a class object.
Run Code Online (Sandbox Code Playgroud)

.米

@interface NList()
@property (weak, nonatomic, readwrite) NSObject *head;
@property (nonatomic,readwrite) NSInteger *size;
@end

@implementation NList
@synthesize size = _size;
- (id) init:(NSInteger *)size {
    //is this even necessary? I don't want object methods.. or do I ?
    if (self){
        _head = nil;
        _size = size;
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

。H

@interface NList : NSObject
@property (nonatomic,readonly) NSInteger *size;
@property (weak, readonly, nonatomic) NSObject *head;

- (void)add:(NSObject *)node;

@end
Run Code Online (Sandbox Code Playgroud)

测试班

- (void)testAdd
{
    NList *testList = [[NList init] alloc];
   // Card *testCardOne = [[Card init] alloc];
   // [testList add:(testCardOne)];
    XCTAssertNotNil(testList.head);
}
Run Code Online (Sandbox Code Playgroud)

我尝试添加行

    self = [[super init] alloc];
Run Code Online (Sandbox Code Playgroud)

到构造函数无济于事。

nlist 声明没有可见的接口

or self = [super init]
Run Code Online (Sandbox Code Playgroud)

抱怨无法初始化类对象!

编辑

我意识到它不是在问我尺寸!构造函数需要一个大小参数...我该怎么做!啊[查找文档]

Bri*_*acy 5

一些东西。

你需要一个默认构造函数

- (id)init {
    self = [super init];
    if (self) {
        self.head = nil;
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

现在您已经有了一个默认构造函数(调用超类构造函数),您需要一个更具体的构造函数来实现您的目的。

- (id)initWithSize:(int)size {
    self = [self init]; // sets head, calls super constructor.
    if (self) {
        self.size = size;
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,最后一个必须位于您的.h文件中,以便可见。而且,在实例化此类时,调用

NList *list = [[NList alloc] initWithSize:mySize];