警告:未找到'+ init'的方法定义 - 但它已实现

时间:2014-07-31 16:48:13

标签: objective-c

我是Objective-C的新手并尝试构建一个简单的类。我现在有一段工作代码,但出于某种原因,我无法摆脱两个警告。我做错了什么?
*如果有任何不同,我正在终端与GCC进行编译。

代码:

#import <objc/Object.h>
#import <stdio.h>

@interface ValueAssignment : Object
{
    char name;
}

+ (void) setVar:(char) x_name;
+ (id) init;
@end

@implementation ValueAssignment

- (void) setVar:(char) x_name{
    name = x_name;
}

- (id) init {
    if(self = [super init]){
        name = ' ';
    }else{
        return nil;
    }
}
@end

/** Main program for the program execution entry **/
int main(int argv, char* argc[])
{
//    id o = [ValueAssignment new];
    id o = [[ValueAssignment alloc] init];

    [o setVar:'9'];

    printf("Bye.\n");
}

编译:

gcc -arch i386 -o hello -l objc test.m

输出:

test.m:26: warning: incomplete implementation of class ‘ValueAssignment’
test.m:26: warning: method definition for ‘+init’ not found
test.m:26: warning: method definition for ‘+setVar:’ not found

编辑:

如果我将实现部分更改为+ (id) init {,那么我会得到以下输出:

test.m: In function ‘+[ValueAssignment setVar:]’:
test.m:16: warning: instance variable ‘name’ accessed in class method
test.m: In function ‘+[ValueAssignment init]’:
test.m:21: warning: instance variable ‘name’ accessed in class method

2 个答案:

答案 0 :(得分:1)

更改界面。您将init声明为类方法而不是实例方法:

+ (id) init;

应该是:

- (id) init;

setVar:方法相同。

除非你有充分的理由不这样做,否则请改变:

id o = [[ValueAssignment alloc] init];

为:

ValueAssignment *o = [[ValueAssignment alloc] init];

答案 1 :(得分:0)

类方法+ init和实例方法-init之间存在差异。