Take a look at this:
#import <Foundation/Foundation.h>
@interface ClassA : NSObject
-(NSString *) method1:(NSString*)str1;
@end
@implementation ClassA
-(NSString *) method1:(NSString*)str1
{
NSLog(@"2. %@ at %p", str1, str1);
str1 = @"foo";
NSLog(@"3. %@ at %p", str1, str1);
return str1;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
NSString *str = @"moo";
NSLog(@"1. %@ at %p", str, str);
ClassA *a = [[ClassA alloc] init];
NSString *b = [a method1:str];
NSLog(@"4. %@ at %p", str, str);
NSLog(@"5. %@ at %p", b, b);
}
return 0;
}
The console log is:
2012-09-11 17:03:16.160 passByValue[1559:403] Hello, World!
2012-09-11 17:03:16.162 passByValue[1559:403] 1. moo at 0x104c42248
2012-09-11 17:03:16.162 passByValue[1559:403] 2. moo at 0x104c42248
2012-09-11 17:03:16.163 passByValue[1559:403] 3. foo at 0x104c421e8
2012-09-11 17:03:16.163 passByValue[1559:403] 4. moo at 0x104c42248
2012-09-11 17:03:16.164 passByValue[1559:403] 5. foo at 0x104c421e8
Notice the address of str is the main function and the address of str1 in method1 is same until str1 is reassigned. Does this follow the principle of passing by Value?
Yes, the value and address of str remains the same after the control comes back to main which follows the principle of passing by value.
So can anyone explain this, or should we live with the fact that str is passed by value and not by reference.