2

i need to know what is the equivalent code for the code below in 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);
    }

this is what i tried :

    -(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];
}

is this a right way ?

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
Bobj-C
  • 5,276
  • 9
  • 47
  • 83

2 Answers2

4

No. You need to return a new instance of the class:

-(MyClass *)func
{
    return [[[[self class] alloc] initWithX:(self.xCoOrdinate - 1)  andY:self.yCoOrdinate] autorelease];
}

Notice we use [[self class alloc] to create a new instance of the current class, MyClass.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • The new instance should be autoreleased because, according to Cocoa's memory management conventions, a method named "func" would not return an owned object. – Ken Thomases Apr 07 '12 at 06:46
1

A few corrections :

public int getXCoOrdinate() {
    return xCoOrdinate;
}

would become :

- (int)getXCoOrdinate
{
    return [self xCoOrdinate];
}

and

public MyClass func() {
    return new MyClass(xCoOrdinate - 1, yCoOrdinate);
}

would become :

+ (MyClass*)func
{
     MyClass* newFunc = [[MyClass alloc] initWithX:0 Y:0];

     if (newFunc)
     {
     }
     return newFunc;
}
Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • The getter is unnecessary, he creates the variables as properties, as shown by his syntax. – Richard J. Ross III Apr 06 '12 at 13:09
  • @RichardJ.RossIII I just tried to explain HOW it should be done in a general fashion. Of course, if he uses `@property` no getters/setters may be needed... – Dr.Kameleon Apr 06 '12 at 13:16
  • The convention in Objective-C is not to prefix getters with "get". You should just call it `xCoordinate` – JeremyP Apr 06 '12 at 13:50
  • @JeremyP Good point. I know, of course. Though I tried NOT to confuse the OP (I just decided to stick to his way of naming the functions). – Dr.Kameleon Apr 06 '12 at 14:04