Reputation: 13994
Imagine I define a variable like this
NSString * a = @"Hello people";
And now I copy the pointer to b so that both a and b point to the location where @"Hello people" is stored in memory (right? Or do I misunderstand how this works?)
NSString * b = a;
Now I want to change b such that a is also updated with the new value. The following does not work since it will point b to a new NSString @"Thanks all"
b = @"Thanks all!";
NSLog(@"%@", a); // still "Hello World"
but what I want is to replace whatever is at the memory location of @"Hello people" so that all pointers to it will update as well.
b = ????;
NSLog(@"%@", a); // Whoa, it still points to the same memory location as b!
Thanks!
Upvotes: 0
Views: 55
Reputation: 150605
In this case you want to use NSMutableString
instead of NSString
.
Because an NSString is immutable, when you change the original, it points to a whole new instance. But if you use an mutable version, the pointer remains unchanged even if the contents change.
However - although this will work, it's a bad idea. Such mutability is fragile. For example, if you have any KVO observers on this property, if the string changes, then no KVO notifications are fired.
Edit
An alternative is to use multiple indirection:
NSString **string;
&string = @"some string";
Now you can have:
NSString **string2 = string;
And changes to string will be propagated to string 2, because although the pointer is the same, the object that it points to will have changed.
Hovewever, you'll need to dereference the pointer to use it, i.e.
NSLog (@"String is: %@", *string);
or
NSLog (@String2 is: %@, *string2);
But you still have that mutability issue.
Upvotes: 1