What's the best way to return 2 (or more) variables from a method in Obj-C?

71 Views Asked by At

What is the best way to return 2 (or more) variables from a method?

Say I want to return 2 integer values (ex. a=10 & b=20) to the (parent) method and load them to the variables myFirst and mySecond.

Both ways work, but which one is better?

1) "Classical" Way:

-(int *)returnMyValues1
{
    int a = 10, b = 20;
    static int myResult[2];

    myResult[0] = a;
    myResult[1] = b;

    return myResult;
}

...

int *result;
result = [viewSeatsAndMore returnMyValues];
myFirst = *result;
mySecond = *(result+1);

2) "Objective" Way:

-(NSArray *)returnMyValues2
{
    int a = 10, b = 20;
    return [NSArray arrayWithObjects:[NSNumber numberWithInt:a], [NSNumber numberWithInt:b], nil];
}

...

NSArray *result = [self returnMyValues2];
myFirst = [[result objectAtIndex:0] intValue];
mySecond = [[result objectAtIndex:1] intValue];

In regard to speed, testing them with 1 million iterations, the 1st way is by 6 seconds faster.

But what about memory? Is the "static int" better than a NSArray?

Does the reservation of memory (due to the static int) not worth the (negligible) speed gain?

Is there a better way?

1

There are 1 best solutions below

1
On BEST ANSWER

It really-really depends on your specific use case. Do you need the method to be fast? If you don't, then just go ahead and use an NSArray, although I'd recommend you use the modern syntax which is more succinct, consequently easier to read:

- (NSArray *)returnAnArray {
    return @[ @42, @1337 ];
}

If you are sure you will only ever need to return two (or a small, fixed number of) integers, you can return a struct too:

typedef struct {
    int first;
    int second;
} TwoInts;

- (TwoInts)returnTwoInts {
    return (TwoInts){ 13, 37 };
}

By the way, your "classic" approach above is… dangerous and ugly. static variables are shared across function calls (even across method calls on different objects). This is, normally, completely different from the expected semantics of a method that returns something related to the object, so it confuses programmers trying to use your code. Don't do that.