One thing that seems to confuse a lot of people with Cocoa is the difference between variables and objects.
You have to keep in mind that when you declare a variable like NSMutableString *mutable
, you are not creating a string. This is just a pointer variable of type NSMutableString*
. Structurally, it's the same as any other pointer — and, as the term "pointer" implies, it just points to something that actually lives elsewhere. Because of this, you technically can assign it to point to any object. But you're not turning that object into a mutable string — you're just lying about what kind of object the variable points to. Once you try to send the object a message that only NSMutableString can respond to, the jig is up!
As Perspx said, if you have a string that you want to mutate, you can use the mutableCopy
method to get — you guessed it — a mutable copy. There are also a lot of NSString methods that don't mutate the string, but let you get a new string with certain changes made (for example, stringByAppendingString:
). You can go a pretty long way with those.