I’m trying to modify the contents of one pointer using another. I want string2 to point to what string1 points to, so that when I modify string2, it modifies string1. How can I do this?
NSString *string1=@"hello";
NSString *string2=string1;
string2=@"changed";
NSLog(@"string1:%@, string2:%@", string1, string2); //"string1:hello, string2:changed"
When you make a second assignment to your
string2variable you are not modifying the contents of what the variable currently refers to, in this case the sameNSStringas variablestring1refers to, but rather your are modifying to whatstring2refers.A picture (code) is worth a thousand words:
Every object and variable has an internal name, usually called its address. Addresses are usually written as hexadecimal numbers, e.g.
0xdeadbeef, the value of the number is not important to you – it is just a label.When you write:
the right-hand side asks Objective-C to create an
NSStringwith the value@"Hello", the result of this is an address, say0xfeeddeaf. The lhs-side asks for a variable capable of holding anNSString *in it – a reference to anNSString; to call this variablestring1; and to store the result of the rhs,0xfeeddeaf, into it.When you now write:
this results in a variable
string2also containing0xfeeddeaf. There is no linkage between the contents ofstring1andstring2, assignment just copies a value (which is an address in the case).Finally when you write:
this creates an
NSStringwith the value of@"changed"with an address, say, of0xbeedcafeand stores that instring2. So nowstring1contains0xfeeddeafwhich is the address of@Hello, andstring2contains0xbeedcafewhich is the address of@"changed".I’m guessing when you write that you’re “trying to modify the contents of one pointer using another” what you want is for
string1andstring2to refer to the same object, whose value you can modify. You can’t modify the value of anNSString, they are non-modifiable (immutable) once created. Instead you have to use anNSMutableStringand you need to use a method to change the value of anNSMutableStringobject – as the above shows if you use assignment you change which object is referred to, not the contents of the object.Assuming you are using ARC[*] then changing your code to:
will accomplish what I think you intend. The first two lines execute similarly to above and you end up with
string1andstring2containing the same address. The third line changes what is at the address they both refer to – you have the linkage you intended.[*] if you are using GC or
retain/releasechange the rhs of the first line to[[NSMutableString alloc] initWithString:"@Hello"]