I did find some discussion on this topic, but it was beyond my current level of understanding. I’m reading through Kochan’s “Programming in Objective-C, 4e” and am on the section about NSString objects. First, the code I’m playing with so I can ask my question:
NSString *strA = @"StringA";
NSString *strB = @"StringB";
NSLog(@"Value of strA: %@",strA);
NSLog(@"Value of strB: %@",strB);
strB = strA; // strB should point to strA's memory location
NSLog(@"New value of strB: %@",strB); //correctly logs as "StringA"
strA = @"StringA has been changed.";
NSLog(@"New value of strB: %@",strB); //logs as "StringA" still
NSLog(@"New value of strA: %@",strA); //correctly logs as "StringA has been changed"
My understanding is that saying strB = strA would mean that strB is pointing to strA’s memory location, so any changes to strA would also go to strB. However, this doesn’t happen. Kochan says it’s supposed to, and to get around it suggests using
strB = [NSString stringWithString: strA];
From what I can see, either method works. I can say strB = strA, then change strA, yet strB still retains the value it received (the value of strA before just changing it).
I thought this might come from NSString being immutable, but if that’s the case, why can I in fact change the values of str1 and str2 after initialization? What am I missing here? Thanks.
As if you didn’t have enough answers to this already…
I think a diagram or three will help you understand what’s going on in your code example.
First, your code does this:
This makes your app’s memory look like this:
On the left are your local variables,
strAandstrB. They are just pointers to objects in memory.In the middle are the string objects. These are pre-created in your app by the compiler because they appeared in your source code.
On the right are the actual characters of the string objects. These are also pre-created in your app by the compiler.
Next, your code does this:
Now your app’s memory looks like this:
Notice that your local variable,
strB, changed, but the objects and the characters didn’t change.Finally, your code does this:
This makes your app’s memory look like this:
Your local variable,
strA, has changed, but the objects and the characters still didn’t change.