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;
}
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With