通過(guò)引用方法調(diào)用參數(shù)傳遞給函數(shù)的參數(shù)的地址復(fù)制到正式的參數(shù)。在函數(shù)內(nèi)部,地址用于訪問(wèn)實(shí)際的參數(shù)在調(diào)用中使用。這意味著參數(shù)所做的更改會(huì)影響傳遞的參數(shù)。
要通過(guò)引用值,參數(shù)指針傳遞的功能,就像任何其他值。因此,需要聲明以下函數(shù)swap(),交換兩個(gè)整型變量的值,指出其參數(shù)的函數(shù)的參數(shù)為指針類型。
/* 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; }
要查看更詳細(xì)的Objective - C 指針,可以查看“Objective-C 指針“一章。
現(xiàn)在,讓我們調(diào)用函數(shù)swap() 通過(guò)在下面的例子作為參考值:
#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 ", a ); NSLog(@"Before swap, value of b : %d ", b ); /* calling a function to swap the values */ [sampleClass swap:&a andNum2:&b]; NSLog(@"After swap, value of a : %d ", a ); NSLog(@"After swap, value of b : %d ", b ); return 0; }
讓我們編譯并執(zhí)行它,它會(huì)產(chǎn)生以下結(jié)果:
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
這表明變化反映的函數(shù)之外,也不像調(diào)用值的變化并不能反映函數(shù)之外。