尝试覆盖init方法时出错

时间:2013-02-19 20:19:55

标签: objective-c

我有一个Square类我试图覆盖一个init方法,.m看起来像这样:

@implementation Square

{
    Rectangle *rect;
}

@synthesize side;

-(int) area
{
    return side * side;
}

-(int) peremiter
{
    return side * 4;
}

-(id) init
{
    return [self init];
}

-(Square *) initWithSide:(int)s
{
    self = [super init];

    if (self)
     [self initWithSide:s];

    return self;
}

@end

我得到的错误是在initWithSide方法中说:

代表init的结果必须立即返回或分配给self

3 个答案:

答案 0 :(得分:2)

这些行:

if (self)
 [self initWithSide:s];

毫无意义,基本上意味着你会一遍又一遍地调用初始化程序。您应该将其更改为执行有用的操作(例如,设置s的值)。另外,您的无参数init方法也是错误的。它应该是:

-(id) init {
    return [super init];
}

但由于其中没有专门的实现,实际上根本不需要它。

答案 1 :(得分:1)

删除当前的init方法并用它们替换它们(不要忘记在接口范围内更新它们):

- (id)init {
    if (self = [super init]) {
        // do whatever you like to to do here
    }
    return self;
}

- (id)initWithSide:(int)s { // but an NSInteger would be more elegant, and the parameter name 's' also would be better to be like 'side'
    if (self = [super init]) {
        [self setSide:s];
    }
    return self;
}

答案 2 :(得分:0)

这是正确的语法:

- (id) initWithSide:(int)s{
   self = [super init];
    if (self){
        //init elements 
    }
    return self;
}
相关问题