Can you return two arguments in objective-c?

孤街醉人 提交于 2019-12-13 11:39:08

问题


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.

(Syntactical help would also be appreciated.)

Thanks,

Nick


回答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"];
}



回答2:


Couldn't you make an NSArray for this?

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



回答3:


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.




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


来源:https://stackoverflow.com/questions/2002745/can-you-return-two-arguments-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!