James James - 5 months ago 12
Objective-C Question

Pointers to the same object Objective-c

I have the following code. When I print out aString it is Goodbye and when i print out bString it is Hellworld. Shouldn't bString be pointing to the same object as aString. I would expect both to print Goodbye. Also when i print out the memory addresses of the pointers they are different memeory addresses. Can someone explain why?

NSString *aString = @"Helloworld";
NSString *bString = aString;

aString = @"Goodbye";


I want bString to point to the same object as aString. So if the value of aString changes then the value of bString also changes and vice-versa. How can I achieve this?

Answer

Here's a visualisation of what's happening in your code, line by line.

aString –––––––––> @"Helloworld"

aString –––––––––> @"Helloworld"
                        ^
                        |
bString –––––––––––––––––

aString –––––––––> @"Goodbye"   @"Helloworld"
                                     ^
                                     |
bString ––––––––––––––––––––––––––––––

As you can see, pointing aString to another object has no effect on the object that bString is already pointing to. You simply end up with two pointers each pointing to different objects.

In order to achieve your desired behaviour of having aString and bString pointing to the same object, which you need to be able to change, you're going to need a mutable object (such as NSMutableString, as Franklin says).

This will allow you to mutate the underlying object, rather than creating and pointing to a new object – therefore aString and bString will stay pointed to the same object after the mutation, allowing them both to observe the same value.

The mutation would simply look like this:

aString –––––––––> @"Helloworld"
                        ^
                        |
bString –––––––––––––––––

aString –––––––––>  @"Goodbye"
                        ^
                        |
bString –––––––––––––––––