目录

Call by value

将参数传递给函数的value call by value方法将参数的实际值复制到函数的形式参数中。 在这种情况下,对函数内部参数所做的更改不会对参数产生影响。

默认情况下,Objective-C编程语言使用call by value方法传递参数。 通常,这意味着函数内的代码不能改变用于调用函数的参数。 考虑函数swap()定义如下 -

/* function definition to swap the values */
- (void)swap:(int)num1 andNum2:(int)num2 {
   int temp;
   temp = num1;   /* save the value of num1 */
   num1 = num2;   /* put num2 into num1 */
   num2 = temp;   /* put temp into num2 */
   return;
}

现在,让我们通过传递实际值来调用函数swap() ,如下例所示 -

#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
/* method declaration */
- (void)swap:(int)num1 andNum2:(int)num2;
@end
@implementation SampleClass
- (void)swap:(int)num1 andNum2:(int)num2 {
   int temp;
   temp = num1;   /* save the value of num1 */
   num1 = num2;   /* put num2 into num1 */
   num2 = temp;   /* put temp into num2 */
}
@end
int main () {
   /* local variable definition */
   int a = 100;
   int b = 200;
   SampleClass *sampleClass = [[SampleClass alloc]init];
   NSLog(@"Before swap, value of a : %d\n", a );
   NSLog(@"Before swap, value of b : %d\n", b );
   /* calling a function to swap the values */
   [sampleClass swap:a andNum2:b];
   NSLog(@"After swap, value of a : %d\n", a );
   NSLog(@"After swap, value of b : %d\n", b );
   return 0;
}

让我们编译并执行它,它将产生以下结果 -

2013-09-09 12:12:42.011 demo[13488] Before swap, value of a : 100
2013-09-09 12:12:42.011 demo[13488] Before swap, value of b : 200
2013-09-09 12:12:42.011 demo[13488] After swap, value of a : 100
2013-09-09 12:12:42.011 demo[13488] After swap, value of b : 200

这表明尽管在函数内部已经更改了值,但值没有变化。

↑回到顶部↑
WIKI教程 @2018