4

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;
}
user1437410
  • 131
  • 1
  • 9

3 Answers3

10

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];
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
5

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.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

This is more related to C than objective-c.

You need to pass the values by references. Your function should be declared like this:

- (void)convertABC2XYZA:(float)a
              B:(float)b 
              C:(float)c 
        outputX:(float *)x 
        outputY:(float *)y 
        outputZ:(float *)z;

and called like this:

[receiver convertABC2XYZA:a B:b C:c outputX:&x outputY:&y outputZ:&z];
J2theC
  • 4,412
  • 1
  • 12
  • 14