I'd like to do a series of string substitutions to removed xml-escaped chars such as '&'
.
1) Is there an existing UIKit function that can do this?
2) If not, what's the best way to do it without leaking memory? Here's the idea:
-(NSString*) unescape:(NSString*)string
{
string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\""];
string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];
string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
return string;
}
But doesn't that leak memory with each assignment? Or does stringByReplacingOccurrencesOfString return autoreleased strings? How do we confirm that stringByReplacingOccurrencesOfString strings are autoreleased? Or should we wrap them with [... autorelease]
?
Even if they are autoreleased, it's preferable to avoid autorelease on the iPhone. (See here). So then we would do:
-(NSString*) unescape:(NSString*)string
{
NSString* string2 = [string stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
// don't release 'string' because we didn't allocate or retain it
NSString* string3 = [string2 stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
[string2 release];
NSString* string4 = [string3 stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
[string3 release];
//...and so on
}
But that's pretty ugly code. What's the best way to write this code to do multiple substitutions? How would you do it?