何时释放瞬态 NSString StringWithFormat?

发布于 2024-11-03 17:01:18 字数 465 浏览 6 评论 0原文

请帮助 iPhone 开发新手。在我的应用程序中,我经常这样做,而 Instruments 将其显示为泄漏。这样做的正确方法是什么?

我正在尝试将数字数据重新格式化为字符串,以便在 NSMutableDictionary 对象中使用。所以我想如果我做这样的事情那就太好了:

[myDict setObject:[NSString stringWithFormat:@"%d", section] forKey:@"Category"];

我不想写 3 行来做到这一点...

NSString *cat = [NSString stringWithFormat:@"%d", section];
[myDict setObject:cat forKey:@"Category"];
[cat release];

如果必须的话我会的,但是这种短暂使用的最佳实践是什么?

Please help a newbie to iPhone development. In my app, I do this a lot, and Instruments shows it as a leak. What is the right way to do this?

I am trying to reformat numeric data as a string for use in NSMutableDictionary objects. So I thought it would be great if I did something like this:

[myDict setObject:[NSString stringWithFormat:@"%d", section] forKey:@"Category"];

I'd hate to have to write 3 lines to do it...

NSString *cat = [NSString stringWithFormat:@"%d", section];
[myDict setObject:cat forKey:@"Category"];
[cat release];

If I have to I will, but what is the best practice for such a transient use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

垂暮老矣 2024-11-10 17:01:18

你不需要释放它。由于 stringWithFormat 不是以 allocinitnewcopy 开头,或 mutableCopy,除非您明确保留它,否则您不负责释放它。

当 Instruments 向您显示泄漏时,它会向您显示泄漏对象的分配位置,但不一定是实际导致泄漏的代码。我怀疑您正在泄漏myDict,因此其中的所有对象也都被泄漏。

You don't need to release it. Since stringWithFormat doesn't start with alloc, init, new, copy, or mutableCopy, you're not responsible for releasing it unless you've explicitly retained it.

When Instruments shows you a leak, it shows you where the leaked object was allocated, but not necessarily the code that's actually causing the leak. I suspect you're leakingmyDict, and thus all the objects inside it are leaked as well.

等你爱我 2024-11-10 17:01:18

你永远不会释放它。已经自动发布了。

您只能释放通过名称以 +alloc+new -copy-mutableCopy 开头的方法提供的对象,或-retain。如果该名称以其他名称开头,则您不拥有它,也不负责发布它。

You never release it. It's autoreleased already.

You only ever release objects which were given to you via methods whose names begin with +alloc, +new -copy, -mutableCopy, or -retain. If the name begins with anything else, you don't own it and are not responsible for releasing it.

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