When you write foo = @"Hello World!";
, foo was pointing to an NSString
object that has the data "Hello World!"
, let's say that this object resides at address 10.
When you write foo = @"Hello everybody!"
, foo
now points to a new object that has the data "Hello everybody!"
, let's say that this object resides at address 50. The first object wasn't modified at all, you just made foo point to another object at another address.
If those strings were mutable, you could modify the content,
NSMutableString *foo = @"Hello World!".mutableCopy; //LEt's say, it's @ adress 10
[foo appendString:@"How is it going?"]; // IT's still @ adress 10, but with new content.
foo now points to an object at address 10, that has modified content "Hello World!How is it going?"
.
In the first case, you couldn't modify NSString
because it doesn't give you any methods to change the data at that address. That's immutability. NSMutableString
on the other hand gives you that ability, by methods like appendString:
and appendString:
. This way you can change the contents of the object at the same address without having to create a new object to make those changes.