问题描述
我想返回一个笛卡尔坐标 (x, y),作为两个 int
s.我看到的唯一方法是创建一个类并返回它的一个实例.
I'd like to return a Cartesian coordinate (x, y), as two int
s. The only way I see is to create a class and return an instance of it.
如何从Objective C中的方法返回两个值?
How to return two values from a method in Objective C?
推荐答案
你只能从一个函数中返回一个值(就像 C 语言一样),但该值可以是任何东西,包括一个结构体.并且由于您可以按值返回结构,因此您可以定义这样的函数(借用您的示例):
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"];
}
这篇关于如何返回两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!