通过引用参数传递

在传递给方法的参数传递中,实际参数的地址被传递给形式参数。因此,从被调用函数返回后,实际参数值将被更改。

@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