views:

82

answers:

4

Why when I code I can do:

NSString *test;

test = @"stack";
test = @"overflow";

without any problems, NSString is not supposed to be immutable?

+6  A: 

The string object is immutable. You are only changing the pointer to a different string.

Lou Franco
+6  A: 

It is immutable. You're not changing the underlying string with those statements, you're creating/using a brand new string. The pointer itself can change as often as you want but that's not the string.

paxdiablo
And it's ok to do this or it's the wrong way to manipulate string.
alex
It is the correct way to handle it. Whenever you do @"Some Text" you are really just creating an autoreleased instance of NSString.
peelman
Ok, so when you use NSMutableString if you can do this with NSString, sorry if my question feels stupid.
alex
@alex, there are no stupid questions, the pursuit of knowledge is rarely a bad thing. One reason you'd use a mutable string is if you didn't want to burden the garbage collector (GC takes time and fragmented memory can be a performance issue). Example: say you have a string that's always of the form 'User:14860' and the only thing that changes is the '14860' bit. You can use a mutable string and just change that bit (assuming length of '14860' is the same) which will not result in any objects becoming garbage-collectable. If instead you kept creating new strings, memory would soon fragment.
paxdiablo
@paxdiablo - Actually, if he's working on the iPhone garbage collection really doesn't come into this. In his case, he'd need to worry about autoreleased strings piling up in an autorelease pool (particularly within a tight loop) or manually managing the memory for each. Also, object allocation / deallocation is one of the most expensive operations you can perform on the iPhone, and you can avoid that using a mutable string.
Brad Larson
+1  A: 

In your code you just "forget" about the old value (stack) and create a new string instance and fill it with "overflow"...

Michael Kessler