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
You can use the
mutableCopymethod, which creates a mutable copy of the receiver and applies to any class which adopts theNSMutableCopyingprotocol (of whichNSStringis one of them):This will create a mutable copy of the string, as a new string instance. In this case it doesn’t apply, as
tempis 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
mutableCopycontains “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
mutableas a pointer to the previously instantiatedNSString.