Reputation: 53
NSString * str1 = @"haha";
NSString * str2 = [str1 copy];
str1 = @"laa";
NSLog(@"str1的地址为:%p", str1);
NSLog(@"str2的地址为:%p", str2);
NSLog(@"str1的值为:%@", str1);
NSLog(@"str2的值为:%@", str2);
as the code above, their memory address is different. but if i remove the third line, their memory address is same. could you tell me the reason? I have searched for a long time,thanks
Upvotes: 2
Views: 74
Reputation: 6992
It's due to optimalization. On iOS, every unique string exists only once in memory - there will always be only one haha
NSString, no matter how many references to it you have, or where you create it. But in third line you change the original string, while the copy remains the same. Therefore, you now have two unique strings.
Upvotes: 1