views:

271

answers:

3

Just wondering if you can return two arguments in an objective c method, for example I'd like to return a cartesian coordinate (x,y), basically two ints. is the only way to do this by creating a class and returning an instance? Is there some other way I'm not thinking of, kind of a beginner here.

any syntactical help would also be appreciated.

Thanks,

Nick

A: 

Couldn't you make an NSArray for this?

return [NSArray arrayWithObjects:coorX, coorY, nil];
Chris Long
dictionaries work better, because you don't have to worry about the order the same way you do an array.
Kenny Winker
Yeah, usually. I guess I was focusing too much on the example the OP gave, since coordinates are always (*x*, *y*).
Chris Long
Thanks everyone for the insight, that makes sense. I'm having a hell of a time trying to figure out this algorithm I'm working on.Thanks,Nick
nickthedude
Using a dictionary / array as the return type is in _most_ cases bad style.
Georg
+16  A: 

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"];
}
gavinb
+2  A: 

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.

Chuck