Should I return an NSMutableString in a method that returns NSString
- by Casey Marshall
Ok, so I have a method that takes an NSString as input, does an operation on the contents of this string, and returns the processed string. So the declaration is:
- (NSString *) processString: (NSString *) str;
The question: should I just return the NSMutableString instance that I used as my "work" buffer, or should I create a new NSString around the mutable one, and return that?
So should I do this:
- (NSString *) processString: (NSString *) str
{
NSMutableString *work = [NSMutableString stringWithString: str];
// process 'work'
return work;
}
Or this:
- (NSString *) processString: (NSString *) str
{
NSMutableString *work = [NSMutableString stringWithString: str];
// process 'work'
return [NSString stringWithString: work]; // or [work stringValue]?
}
The second one makes another copy of the string I'm returning, unless NSString does smart things like copy-on-modify. But the first one is returning something the caller could, in theory, go and modify later. I don't care if they do that, since the string is theirs. But are there valid reasons for preferring the latter form over the former? And, is either stringWithString or stringValue preferred over the other?