How to return two values?

20,133

Solution 1

You can only return one value from a function (just like C), but the value can be anything, including a struct. And since you can return a struct by value, you can define a function like this (to borrow your example):

-(NSPoint)scalePoint:(NSPoint)pt by:(float)scale
{
    return NSMakePoint(pt.x*scale, pt.y*scale);
}

This is only really appropriate for small/simple structs.

If you want to return more than one new object, your function should take pointers to the object pointer, thus:

-(void)mungeFirst:(NSString**)stringOne andSecond:(NSString**)stringTwo
{
    *stringOne = [NSString stringWithString:@"foo"];
    *stringTwo = [NSString stringWithString:@"baz"];
}

Solution 2

You can either return one value directly and return another by reference, as shown in gs's answer, or create a struct type and return that. For example, Cocoa already includes a type to identify points on a 2D plane, NSPoint.

Solution 3

Couldn't you make an NSArray for this?

return [NSArray arrayWithObjects:coorX, coorY, nil];

Solution 4

I recommend you to return an NSDictionary, inside Dictionary you can store and send any object type and any number of variables.

-(NSDictionary*)calculateWith:(id)arg
{
NSDictionary *urDictionary =@{@"key1":value1,@"Key2":value2,.....};
return  urDictionary;
}
Share:
20,133
nickthedude
Author by

nickthedude

Founder, CEO and Head Hacker at Tiny Mobile Inc. Mostly specialize in iOS but know a little about a lot. I'm a former designer video producer turned coder living in the Bay area.

Updated on August 25, 2020

Comments

  • nickthedude
    nickthedude almost 4 years

    I'd like to return a Cartesian coordinate (x, y), as two ints. The only way I see is to create a class and return an instance of it.

    How to return two values from a method in Objective C?

  • Stefan
    Stefan over 14 years
    Using a dictionary / array as the return type is in most cases bad style.
  • gavinb
    gavinb about 10 years
    And now with the introduction of Swift, you can return multiple arguments from functions using tuples. See The Swift Programming Language for details.