user1437410
user1437410

Reputation: 131

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;
}

Upvotes: 4

Views: 1489

Answers (3)

rob mayoff
rob mayoff

Reputation: 386018

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];

Upvotes: 10

J2theC
J2theC

Reputation: 4452

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];

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 360026

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.

Upvotes: 5

Related Questions