xiaotao Li
xiaotao Li

Reputation: 53

why is the nstring obj's memory address different from the copied one in iOS dev ?

     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

Answers (1)

mag_zbc
mag_zbc

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

Related Questions