iPhone - 关于内存使用情况的NSString和NSMutableString之间的区别

时间:2011-11-17 20:36:43

标签: iphone ios cocoa-touch ipad

我有一块必须要解析的文本。这是一个像

这样的模板
  

“亲爱的$ name,我们需要你的$ vehicle的注册号,bla bla”......

想象这个1000个字符长,有很多关键变量,比如$ name,$ vehicle等。

此文字存储在#define

在运行时,我必须像这样解析这个模板和其他20个模板,用真实值替换关键变量,比如“亲爱的John,......”。

我使用NSString变量来存储初始文本,然后使用这些行

NSString *start = TEMPLATE1;
start = [start stringByReplacingOccurrencesOfString:NAME withString:realName];
start = [start stringByReplacingOccurrencesOfString:VEHICLE withString:realVehicle];

所以一个和代码工作得很快,但有人建议使用NSMutableString作为起始变量,因为它会占用更少的内存。
这是对的吗? 值得改变吗?

1 个答案:

答案 0 :(得分:0)

这样做是合理的:

NSMutableString *text = [NSMutableString stringWithString:TEMPLATE1];
[text replaceOccurrencesOfString:NAME withString:realName options:0 range:NSMakeRange(0, [text length])];
[text replaceOccurrencesOfString:VEHICLE withString:realVehicle options:0 range:NSMakeRange(0, [text length])];

但是如果你的代码已经“快速且良好地工作”,我就不会费心去改变它了。