Pass by reference parameter passing
suggest changeIn pass by reference, the address of the argument is passed. Writing through that pointer changes the caller’s variable. Objective-C does this with C pointers; objects themselves are already pointers.
@interface SwapClass : NSObject
- (void)num:(int *)num1 andNum2:(int *)num2;
@end
@implementation SwapClass
-(void) num:(int*)num1 andNum2:(int*)num2{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
@end
Calling the methods:
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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents