Should I return an NSMutableString in a method that returns NSString
Posted
by Casey Marshall
on Stack Overflow
See other posts from Stack Overflow
or by Casey Marshall
Published on 2010-05-29T06:08:36Z
Indexed on
2010/05/29
6:12 UTC
Read the original article
Hit count: 295
objective-c
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?
© Stack Overflow or respective owner