在 iPhone 上正确重用 NSMutableString
在iPhone上使用objective-c,这段代码有什么问题? 是不是内存泄漏了?为什么? 我该如何正确地做到这一点?
NSMutableString *result = [NSMutableString stringWithFormat:@"the value is %d", i];
...然后在我的代码中...我可能需要将其更改为:
result = [NSMutableString stringWithFormat:@"the value is now %d", i];
我需要第二次使用 stringWithFormat ...但这不是创建一个新字符串并且没有正确释放旧字符串吗?
Using objective-c on the iPhone, what is wrong with this code?
Is it leaking memory? Why?
How would I do this correctly?
NSMutableString *result = [NSMutableString stringWithFormat:@"the value is %d", i];
... then later in my code... I might need to change this to:
result = [NSMutableString stringWithFormat:@"the value is now %d", i];
I need to use stringWithFormat a 2nd time... but isn't that creating a NEW string and not correctly freeing the old one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,它不会泄漏内存,因为
stringWithFormat:
返回一个自动释放的对象。No, it doesn't leak memory because
stringWithFormat:
returns an autoreleased object.您可以对已经存在的 NSMutableString 使用实例方法“setString”,如下所示:
You could use the instance method "setString" for your already existing NSMutableString, like this:
如果您确实想重用该字符串,则可以使用类似的内容
但是,除非您注意到性能/内存问题,否则只需使用使用
不可变对象通常更容易,因为它们在您的脚下无法更改。
If you really want to reuse the string, you can use something like
However, unless you notice a performance/memory problem, just use
It's generally easier to work with immutable objects because they can't change under your feet.
在我看来,您所拥有的似乎是用新内容替换可变字符串的自然方法,除非您在其他地方有对同一可变字符串的其他引用。
如果您没有对它的其他引用,并且您只是为了提高性能/内存占用而重用该字符串,那么这听起来像是过早的优化。
顺便说一句,您不拥有通过 stringWithFormat: 获得的字符串,因此您不需要(确实不能)释放它。
What you have seems to me to be the natural way to replace a mutable string with new content, unless you have other references to the same mutable string elsewhere.
If you don't have other references to it and you are reusing the string only to improve performance/memory footprint, that sounds like premature optimisation.
By the way, you do not own a string you obtain via stringWithFormat: so you do not need to (Indeed must not) release it.