我需要知道下面的代码在 Objective-C 中的等效代码是什么
public MyClass(int x, int y) {
xCoOrdinate = x;
yCoOrdinate = y;
}
public int getXCoOrdinate() {
return xCoOrdinate;
}
public int getYCoOrdinate() {
return yCoOrdinate;
}
public MyClass func() {
return new MyClass(xCoOrdinate - 1, yCoOrdinate);
}
这是我尝试过的:
-(id)initWithX:(int )X andY:(int)Y
{
if(self = [super init])
{
self.xCoOrdinate = X;
self.yCoOrdinate = Y;
}
return self;
}
-(MyClass *)func
{
return [self initWithX:(self.xCoOrdinate -1) andY:self.yCoOrdinate];
}
这是正确的方法吗?
最佳答案
没有。您需要返回该类的一个新实例:
-(MyClass *)func
{
return [[[[self class] alloc] initWithX:(self.xCoOrdinate - 1) andY:self.yCoOrdinate] autorelease];
}
请注意,我们使用 [[self class alloc]
创建当前类 MyClass
的新实例。
关于Java 类到 Objective-C 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10043574/