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?
Any cocoa method which returns a new object via a method that does not start with
initor contain the wordcopywill return an autoreleased object. So the above code should have noleaks.Although it may be easier to use a NSMutableString here. Then you just modify the string in place rather than creating a pile of autoreleased string objects, which should make things cleaner.
Also, how about a dictionary of mappings that you iterate through, finding the
keyand replacing with thevalueof each item. Maybe even save this as a plist in your app for easy tweaking later.