Objective c 设置实例方法的返回值
我知道实例方法在执行完后可以返回一个值,但我不知道如何设置和获取该值,我知道如何设置参数,但如何设置方法本身的返回类型 因此,这是实例方法实现:Objective c 设置实例方法的返回值,objective-c,methods,return,instance,Objective C,Methods,Return,Instance,我知道实例方法在执行完后可以返回一个值,但我不知道如何设置和获取该值,我知道如何设置参数,但如何设置方法本身的返回类型 因此,这是实例方法实现: -(int) returnInteger: (id) anString: (int) anNumber{ 要设置它的参数,我需要: [self returnInteger: (id) returnNSString: (int) 100]; 但是我如何设置“returnInteger本身”的值呢?我想知道如何在它的实现内部以及何时调用它(当它执行
-(int) returnInteger: (id) anString: (int) anNumber{
要设置它的参数,我需要:
[self returnInteger: (id) returnNSString: (int) 100];
但是我如何设置“returnInteger本身”的值呢?我想知道如何在它的实现内部以及何时调用它(当它执行时)设置I
还有一个问题
如果我在方法中将它的第一个参数设置为100,当我调用它时,我想向它添加100,我该怎么做?我试过了,但没有成功
[self returnInteger: (id) returnNSString: (int) + 100];
我仍然不确定你在问什么,但这里有一个可能有用的例子
@interface Juniper : NSObject
// Return type int, first parameter type NSString * and named s,
// second parameter type int and named i. Method's name is
// addNumberInString:toInt:
- (int)addIntInString: (NSString *)s toInt: (int)i;
@end
@implementation Juniper
- (int)addIntInString: (NSString *)s toInt: (int)i
{
// Extract int from argument named s
int intFromString = [s intValue];
// Add that int to argument named i and end
// method, returning the result of addition
return intFromString + i;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
Juniper * j = [[Juniper alloc] init];
// Execute the method, store the return value
int result = [j addIntInString:@"100" toInt:15];
// Display the return value so we know it worked.
NSLog(@"%d", result);
}
return 0;
}
这没有什么意义;这似乎是建立在对方法如何工作的误解上的。要从方法中获取值,可以调用它,传递参数,并在其主体中包含一条
return
语句。“方法本身的价值”和“在实现内部和调用时都设置它”是没有意义的,而且声明和调用并没有做你认为他们在做的事情。也许,如果你详细说明你正在努力实现的目标,我们会更有帮助。。因为声明本身的返回类型是(int)而不是(void),所以在执行完成时应该能够返回一个整数-我没有任何“计划”我只是想知道为什么我在我的任何一本关于obj cOr的书中都没有解释过这一点,至少要将返回类型为整数的方法的名称指定为一个数字,就像我在传递它的参数时所做的那样。将int这样的数据类型分配给实例方法返回类型还有什么意义?