按值傳遞參數(shù)給函數(shù)的方法調(diào)用復(fù)制到正式參數(shù)的函數(shù)參數(shù)的實(shí)際值。在這種情況下,該函數(shù)內(nèi)的參數(shù)所做的更改參數(shù)沒(méi)有影響。
默認(rèn)情況下,使用的Objective-C編程語(yǔ)言調(diào)用值法來(lái)傳遞參數(shù)。在一般情況下,這意味著,在一個(gè)函數(shù)中的代碼可以用來(lái)調(diào)用該函數(shù)的參數(shù)不會(huì)改變??紤]函數(shù)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; }
現(xiàn)在,讓我們通過(guò)在下面的示例中的實(shí)際值作為調(diào)用函數(shù)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 ", 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: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
這表明,盡管它們均已改變,在函數(shù)內(nèi)部的值中沒(méi)有任何改變。