目标C中的“this.x = x”等效?

时间:2012-10-25 21:14:18

标签: objective-c cocoa scope

以下是Java中的示例构造函数:

public Board(int row, int column)
{
    this.row = row;
    this.column = column;
}

...

int row;
int column;

这是我在Objective C中的方法我正在尝试做同样的事情:

- (void) setSquares: (int) row:(int) column
{
    self.row = row; // <-- Error
    self.column = column;// <-- Error
}

...

int row;
int column;

正如您所看到的,我得到2个错误,因为编译器认为我正在尝试访问2个属性,一个称为行,一个称为列。我知道这是你想要访问属性的方式但是你怎么想'改变范围'以便我可以将局部变量设置为方法的参数?我如何在Objective C中做到这一点?

3 个答案:

答案 0 :(得分:1)

目标C中的例程写得不正确。

应该是:

-(void)setSquares:(int)row col:(int)column{
    self.row = row;
    self.column = column;
}

答案 1 :(得分:1)

Java构造函数通常会这样翻译:

@interface Board : NSObject

@property (nonatomic, assign) int row;
@property (nonatomic, assign) int column;

@end

@implementation Board

- (id)initWithRow:(int)row andColumn:(int)column {
    if (self = [super init]) {
        self.row = row;
        self.column = column;
    }
    return self;
}

@end

答案 2 :(得分:1)

只需重命名方法参数:

- (void)setSquares:(int)newRow col:(int)newColumn
{
    row = newRow;
    column = newColumn;
}