字符串操作没有内存泄漏? [英] String manipulation without memory leaks?
问题描述
我想做一系列字符串替换来删除xml转义的字符,例如'& amp;'
。
I'd like to do a series of string substitutions to removed xml-escaped chars such as '&'
.
1)有没有可以做到这一点的现有UIKit函数?
1) Is there an existing UIKit function that can do this?
2)如果没有,最好的方式做它没有泄漏记忆?这里的想法:
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;
}
但是不是泄漏内存与每个赋值或者stringByReplacingOccurrencesOfString返回自动释放字符串?我们如何确认stringByReplacingOccurrencesOfString字符串是自动释放?或者我们应该用 [... autorelease] / code>?
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]
?
即使它们是自动释放的,最好避免在iPhone上自动释放(见这里)。那么我们会这样做:
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?
推荐答案
任何可可方法通过不以<$ c开头的方法返回一个新对象$ c> init 或包含单词 copy
将返回一个自动释放的对象。所以上面的代码应该有noleaks。
Any cocoa method which returns a new object via a method that does not start with init
or contain the word copy
will return an autoreleased object. So the above code should have noleaks.
虽然这里可能更容易使用NSMutableString。然后你只是修改字符串在原地,而不是创建一堆自动释放的字符串对象,这应该使事情更清洁。
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.
此外,如何迭代的映射字典通过,找到键
,并替换为每个项目的值
。也许可以保存为一个plist在您的应用程序,以便以后轻松调整。
Also, how about a dictionary of mappings that you iterate through, finding the key
and replacing with the value
of each item. Maybe even save this as a plist in your app for easy tweaking later.
这篇关于字符串操作没有内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!