在 Objective-C 中通过引用调用函数

将参数传递给函数的通过引用调用方法将参数的地址复制到形式参数中。 在函数内部,地址用于访问调用中使用的实际参数。 这意味着对参数所做的更改会影响传递的参数。

要通过引用传递值,参数指针就像任何其他值一样传递给函数。 因此,相应地,您需要将函数参数声明为指针类型,如以下函数 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;
}

要查看有关 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;     /* save the value of num1 */
   *num1 = *num2;    /* put num2 into num1 */
   *num2 = temp;     /* put temp into num2 */
  
   return;
   
}

@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:27:17.716 demo[6721] Before swap, value of a : 100
2013-09-09 12:27:17.716 demo[6721] Before swap, value of b : 200
2013-09-09 12:27:17.716 demo[6721] After swap, value of a : 200
2013-09-09 12:27:17.716 demo[6721] After swap, value of b : 100

这表明更改也反映在函数外部,这与按值调用不同,后者的更改不会反映在函数外部。

objective_c_functions.html