通過引用引數傳遞
在傳遞給方法的引數傳遞中,實際引數的地址被傳遞給形式引數。因此,從被呼叫函式返回後,實際引數值將被更改。
@interface SwapClass : NSObject
-(void) swap:(int)num1 andNum2:(int)num2;
@end
@implementation SwapClass
-(void) num:(int*)num1 andNum2:(int*)num2{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
@end
呼叫方法:
int a = 10, b =20;
SwapClass *swap = [[SwapClass alloc]init];
NSLog(@"Before calling swap: a=%d,b=%d",a,b);
[swap num:&a andNum2:&b];
NSLog(@"After calling swap: a=%d,b=%d",a,b);
輸出:
2016-07-31 00:01:47.067 Test[5260:83491] Before calling swap: a=10,b=20
2016-07-31 00:01:47.070 Test[5260:83491] After calling swap: a=20,b=10