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 ?

2
  • Are you compiling with or without ARC, and is this code targeting iOS or OS X? Commented Apr 6, 2012 at 12:53
  • @jlehr compiling without ARC and targeting iOS Commented Apr 6, 2012 at 13:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The new instance should be autoreleased because, according to Cocoa's memory management conventions, a method named "func" would not return an owned object.
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;
}

4 Comments

The getter is unnecessary, he creates the variables as properties, as shown by his syntax.
@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...
The convention in Objective-C is not to prefix getters with "get". You should just call it xCoordinate
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.