Objective-C 值调用函数
将参数传递给函数的按 值调用 方法将参数的实际值复制到函数的形式参数中。在这种情况下,对函数内参数所做的更改对参数没有影响。
默认情况下,Objective-C 编程语言使用按 值调用 方法传递参数。通常,这意味着函数中的代码无法更改用于调用函数的参数。考虑函数 swap() 的定义如下:
/* 定义一个交换值的函数 */- (void)swap:(int)num1 andNum2:(int)num2 {int temp;temp = num1; /* 保存 num1 的值到 temp */num1 = num2; /* 将 num2 赋值给 num1 */num2 = temp; /* 把 temp 赋值给 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;num1 = num2;num2 = temp;}@endint 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;}
结果如下:
2022-07-09 12:27:17.716 demo[6721] Before swap, value of a : 1002022-07-09 12:27:17.716 demo[6721] Before swap, value of b : 2002022-07-09 12:27:17.716 demo[6721] After swap, value of a : 2002022-07-09 12:27:17.716 demo[6721] After swap, value of b : 100
这表明,虽然这些值在函数内部发生了更改,但它们没有变化。