mutliple output arguments from a method

boyfarrell

Registered
Hello.

I making a simple 'getter'. However rather than it returning 1 variable as an output I want to return 3.

For example in objective-c you could write:

Code:
@implementation AnObject;

-(int) getNumber;
{
       return number;
}

How would it work for a multiple of outputs? Something like this:
Code:
@implementation AnObjectAgain;

-(int) num1: (int) num2: (int) num3 getNumbers;
{
       return number1;
       return number2;
       return number3;
}
 
You can't. I don't think this is possible in any known programming language either.

There are a few ways around this. One way is to return a struct or a class which holds the values you want to hold. The other way is to pass in pointers to the function and let the function set values to these pointers.

Here are 2 examples:
Code:
- (void)getValues:(int *)num1 num2:(int *)num2 num3:(int *)num3
{
    *num1 = number1;
    *num2 = number2;
    *num3 = number3;
}

// call it like so:
int n1, n2, n3;
[myObject getValues:&n1 num2:&n2 num3:&n3];

Code:
typedef struct
{
    int num1, num2, num3;
} myStruct;

- (myStruct)returnValues
{
    myStruct s;
    s.num1 = number1;
    s.num2 = number2;
    s.num3 = number3;
    return s;
}

You could also do it with a class, but that's a little more overhead, and is unnecessary if you don't have complex data types.

BTW if you don't know C already, I would highly recommend you get a book on it and learn the basics. It will help you a lot down the road with Objective-C.
 
kainjow said:
You can't. I don't think this is possible in any known programming language either.

You can in MATLAB :) However, using a struct or a class like you proposed would be the way I'd go about solving this problem in more conventional languages.
 
Yeah I was just going to mention the MATLAB connection!
Code:
[number1, number2, number3] = myFunction(input, arguments)
God bless MATLAB.

Anyway, back to objective-c!

I have just been messing with the structures before I read your post. I ran into a bit of trouble but will try your suggestions. Cheers.
 
Back
Top