What is an actual example of the difference between NSString to NSMutablestring could look like?

StackOverflow https://stackoverflow.com/questions/15188044

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

有帮助吗?

解决方案

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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top