在 iPhone 上正确重用 NSMutableString

发布于 2024-09-07 02:35:52 字数 373 浏览 6 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

绮烟 2024-09-14 02:35:52

不,它不会泄漏内存,因为 stringWithFormat: 返回一个自动释放的对象。

No, it doesn't leak memory because stringWithFormat: returns an autoreleased object.

神爱温柔 2024-09-14 02:35:52

您可以对已经存在的 NSMutableString 使用实例方法“setString”,如下所示:

[ result setString:[NSString stringWithFormat:@"the value is now %d", i] ];

You could use the instance method "setString" for your already existing NSMutableString, like this:

[ result setString:[NSString stringWithFormat:@"the value is now %d", i] ];
泪冰清 2024-09-14 02:35:52

如果您确实想重用该字符串,则可以使用类似的内容

[result setString:@""];
[result appendFormat:@"the value is now %d", i];

但是,除非您注意到性能/内存问题,否则只需使用使用

NSString *result = [NSString stringWithFormat:@"the value is %d", i];

/* ... */

result = [NSString stringWithFormat:@"the value is now %d", i];

不可变对象通常更容易,因为它们在您的脚下无法更改。

If you really want to reuse the string, you can use something like

[result setString:@""];
[result appendFormat:@"the value is now %d", i];

However, unless you notice a performance/memory problem, just use

NSString *result = [NSString stringWithFormat:@"the value is %d", i];

/* ... */

result = [NSString stringWithFormat:@"the value is now %d", i];

It's generally easier to work with immutable objects because they can't change under your feet.

假装不在乎 2024-09-14 02:35:52

在我看来,您所拥有的似乎是用新内容替换可变字符串的自然方法,除非您在其他地方有对同一可变字符串的其他引用。

如果您没有对它的其他引用,并且您只是为了提高性能/内存占用而重用该字符串,那么这听起来像是过早的优化。

顺便说一句,您不拥有通过 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文