Question about the concept of immutability


Enjoying the book - thanks Aaron

I have a question about the concept of immutable objects

I get that mutable objects can be changed and the idea that immutable ones cant be

so why does the follow code snippet run

    NSString * testString = @"hello there";
    testString =@"hello there again!";

and not generate an error when changing testString?

it obviously changes the string because it logs hello there again


Excellent question. It’s a subtle difference, but in your example you’re not changing the object that testString points to, you’re changing where testString points.

If we assume for a moment that there’s no such thing as ARC, or garbage collection, after your code snippet there is still a lonely NSString object representing “hello there” floating in memory somewhere, never to be seen again, because you’ve taken away the only way for the code to interact with it. You’ve changed the pointer to point to a different NSString object, one that says “hello there again”.

C does have a way to declare pointers such that they cannot be redirected like this, using the const keyword. If you place it in the right location in your declaration, you can prevent the reassignment:

NSString * const testString = @"hello there";
testString =@"hello there again!";  // The compiler will throw an error here

I’m not sure whether Objective-C has another way to do this, but since it’s a superset of C, the above works fine.


thanks macintux for a clear explanation and a fast response .

also for making clear what const does - i’ve seen it in examples elsewhere.


You’re welcome. const actually can be used in a different spot in the declaration to indicate that the object is immutable:

const int * a;  // Means that the integer reference inside a cannot be changed
int const * a;  // Same thing as above
int * const a;  // Means that the pointer a cannot be made to point to a different integer

I highly recommend Expert C Programming: Deep C Secrets by Peter van der Linden for much, much, much more information on C pointers and declarations. Great book.


Out of curiosity, what causes the 1st string to stop floating around on iOS? On Mac OS, garbage collection would ‘clean up’ on what event?