Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get multiple output from a single method in Objective-c

I have my own class and am writing a method with multiple input (three float values) and multiple output (three float values). I don't figure out how I can get multiple output from a single method. Any ideas?

My current method looks like this:

- (void)convertABC2XYZA:(float)a
                  B:(float)b 
                  C:(float)c 
            outputX:(float)x 
            outputY:(float)y 
            outputZ:(float)z 
{
    x = 3*a + b;
    y = 2*b;
    z = a*b + 4*c;
}
like image 450
user1437410 Avatar asked Dec 07 '22 13:12

user1437410


2 Answers

One way to “return” multiple outputs is to pass pointers as arguments. Define your method like this:

- (void)convertA:(float)a B:(float)b C:(float) intoX:(float *)xOut Y:(float *)yOut Z:(float)zOut {
    *xOut = 3*a + b;
    *yOut = 2*b;
    *zOut = a*b + 4*c;
}

and call it like this:

float x, y, z;
[self convertA:a B:b C:c intoX:&x Y:&y Z:&z];

Another way is to create a struct and return it:

struct XYZ {
    float x, y, z;
};

- (struct XYZ)xyzWithA:(float)a B:(float)b C:(float)c {
    struct XYZ xyz;
    xyz.x = 3*a + b;
    xyz.y = 2*b;
    xyz.z = a*b + 4*c;
    return xyz;
}

Call it like this:

struct XYZ output = [self xyzWithA:a B:b C:c];
like image 194
rob mayoff Avatar answered Dec 11 '22 11:12

rob mayoff


Methods in Objective-C (unlike, say, Python or JavaScript) can only return at most 1 thing. Create a "thing" to contain the 3 floats you want to return, and return one of those instead.

Instead of returning, you can use output parameters.

like image 23
Matt Ball Avatar answered Dec 11 '22 12:12

Matt Ball