看看这个:
#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 的地址是 main 函数,在 str1 被重新分配之前,method1 中的 str1 的地址是相同的。这是否遵循按值传递的原则?
是的,控制回到main后str的值和地址保持不变,遵循传值原则。
那么任何人都可以解释这一点,还是我们应该接受 str 是按值传递而不是按引用传递的事实。