これを見てください:
#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;
}
コンソール ログは次のとおりです。
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
str のアドレスがメイン関数であり、method1 の str1 のアドレスは、str1 が再割り当てされるまで同じであることに注意してください。これは値渡しの原則に従っていますか?
はい、制御が値渡しの原則に従うメインに戻った後も、str の値とアドレスは同じままです。
したがって、誰でもこれを説明できますか、または str が参照ではなく値で渡されるという事実を受け入れる必要があります。