xcode 你能在objective-c中返回两个参数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2002745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:02:29  来源:igfitidea点击:

Can you return two arguments in objective-c?

objective-cxcodemethodsarguments

提问by nickthedude

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.

只是想知道是否可以在客观 c 方法中返回两个参数,例如我想返回笛卡尔坐标 (x,y),基本上是两个整数。是通过创建一个类并返回一个实例来做到这一点的唯一方法吗?有没有我没有想到的其他方式,这里是初学者。

(Syntactical help would also be appreciated.)

(语法帮助也将不胜感激。)

Thanks,

谢谢,

Nick

缺口

回答by gavinb

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):

您只能从函数中返回一个值(就像 C 语言一样),但该值可以是任何东西,包括结构体。并且由于您可以按值返回结构,因此您可以定义这样的函数(借用您的示例):

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

回答by Chris Long

Couldn't you make an NSArrayfor this?

你不能NSArray为此做一个吗?

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

回答by Chuck

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.

您可以直接返回一个值并通过引用返回另一个值,如gs's answer所示,或者创建一个结构类型并返回它。例如,Cocoa 已经包含一个类型来识别 2D 平面上的点,NSPoint

回答by Jeba Moses

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

我建议您返回一个 NSDictionary,在 Dictionary 中您可以存储和发送任何对象类型和任意数量的变量。

-(NSDictionary*)calculateWith:(id)arg
{
NSDictionary *urDictionary =@{@"key1":value1,@"Key2":value2,.....};
return  urDictionary;
}