Question

I'v been looking around in the questions here and could not find simple example to point me the difference while I was testing some code of my own to test the differentiation.

From what I understand, in an "immutable" string such as 'NSString', I could not preform any 'NSString' methods to modify the string, such as:

NSString *s = @"cat";

    s = [NSString stringWithString:@"blamp"];

    NSLog(@"%@", s);

But it does work..

Please try to give me and other newbies out there a very simple example of what won't work and why. tnx

Was it helpful?

Solution

The statement :

s = [NSString stringWithString:@"blamp"];

actually creates a new memory location for the string "blamp" and the old address of s gets replaced by this new address.

And you get the feel that the same s is updated!!! Actually the pointer now points to some other memory addresss.


String manipulation means changing the same string : as if you try

NSString *s = @"cat";
[s appendString:@"s"];//tries to append to the same. this will through error.
//the above works with NSMutableString.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top