问题描述
我问了一个类似的问题,但我无法让它完全正常工作。我正在构建一个iPhone应用程序,我想从不同的文件调用一个方法。我认为最简单的方法就是在另一个文件中创建一个方法,并从其他文件中调用该方法。
I asked a similar question, but I couldn't get it working exactly. I'm building an iPhone app, and there is a method that I want called from different files. I figured the easiest way would simply be to make a method in another file, and call the method from the other files.
这是一些问题。我需要在传递多个值后从该方法返回多个值。例如,我传递它:(int,int,int,string,string)
。并且它们需要在更改后返回所有这些值。有人向我展示了这段代码:
Here are some problems. I need to return multiple values from the method, after passing it multiple values. For example, I'm passing it: (int, int, int, string, string)
. And it needs to return all of those values, after they have been changed. Someone showed me this code:
- (NSDictionary *)EndOfTurn:(int)varTurns withFatness:(int)varFatness
{
varTurns--;
if (varTurns <= 0) {
varFatness = varFatness - 5;
}
else {
varFatness += 2;
}
return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:varFatness], @"FATNESS", [NSNumber numberWithInt:varTurns], @"TURNS", nil];
}
但是,此代码不起作用,我需要更多信息,以真正了解它。让我们假设我传递了这些值:
However, this code doesn't work, and I need some more information to really understand it. Let's assuming I'm passing it these values:
int varMoney;
int varNumSheep;
int varNumShepherds;
NSString *test1;
NSString *test2;
所以我需要从方法中获取所有这些值。
So I need to get all of these values back from the method.
如何在头文件中声明这一点?这应该是一个Objective-C文件,但你可以给我整个文件的代码,这样我就可以看到 @implementation
和 @end
,等等。另外,我如何调用此方法?
How do I declare this in the header file? This should be in an Objective-C file, but could you give me the code for the entire file so I can see where it would go with the @implementation
and @end
, whatnot. Also, how would I call this method?
推荐答案
因为您只能从C和C-中的任何方法返回单个值派生语言,您只需返回一个代表所有其他值的值。这是您的示例代码使用 NSDictionary
进行的操作。
Since you can only return a single value from any method in C and C-derived languages, you simply need to return a single value that represents all of your other values. This is what your sample code is doing with an NSDictionary
.
示例代码是正确的,即使它是一个与常见的Objective-C风格相反。
The sample code is correct, even if it's a bit contrary to common Objective-C style.
您在头文件中声明的只是方法的声明,即:
What you declare in the header file is simply the declaration of the method, that is:
@interface MyClass : NSObject
- (NSDictionary *)EndOfTurn:(int)varTurns withFatness:(int)varFatness;
@end
在源文件中,然后:
@implementation MyClass
// code, as given above
@end
这篇关于从Objective-C中的方法返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!