views:

274

answers:

2

I have a NSString and I want to write its value to a NSMutableString. Is this valid:

NSString *temp = [NSString stringWithString:@"test"];
NSMutableString *mutable = temp;

I ask because although this seems doable, I would think that this would assign both temp and mutable to the same address space. I have this question a lot when passing values into a method or returning values from a method. Sometimes I see other people do this or create the mutable string with stringWithString or initWithString. Thanks

+10  A: 

You can use the mutableCopy method, which creates a mutable copy of the receiver and applies to any class which adopts the NSMutableCopying protocol (of which NSString is one of them):

NSString *temp = [NSString stringWithString:@"test"];
NSMutableString *mutable = [temp mutableCopy];

This will create a mutable copy of the string, as a new string instance. In this case it doesn't apply, as temp is an autoreleased string, but you would otherwise need to release the old string that you have made a copy of, if you no longer need it.

Since mutableCopy contains "copy", then you need to memory-manage the new string (you take ownership of it according to the Apple Object Ownership Policy).

The method that you have used simply assigns mutable as a pointer to the previously instantiated NSString.

Perspx
+5  A: 

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.

Chuck