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;}
要查看有关 Objective-C 指针的更多详细信息,可以查看 Objective-C 指针 一章。
现在,让我们通过如下实例中的引用传递值来调用函数 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;return;}@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
这表明,更改也反映在函数外部,不同于按值调用,其中更改不会反映在函数外部。