Objective-c-function-call-by-reference
提供:Dev Guides
Objective-Cの参照による関数呼び出し
引数を関数に渡す*参照による呼び出し*メソッドは、引数のアドレスを仮パラメーターにコピーします。 関数内では、呼び出しで使用される実際の引数にアクセスするためにアドレスが使用されます。 これは、パラメーターに加えられた変更が、渡された引数に影響することを意味します。
参照によって値を渡すために、引数ポインターは他の値と同様に関数に渡されます。 したがって、次の関数* swap()*のように、関数のパラメーターをポインター型として宣言する必要があります。この関数は、引数が指す2つの整数変数の値を交換します。
/*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-ポインターの詳細を確認するには、link:/objective_c/objective_c_pointers [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
これは、値の呼び出しが関数の外部に反映されない値とは異なり、変更が関数の外部にも反映されていることを示しています。