何时释放瞬态 NSString StringWithFormat?
请帮助 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不需要释放它。由于
stringWithFormat
不是以alloc
、init
、new
、copy
开头,或mutableCopy
,除非您明确保留它,否则您不负责释放它。当 Instruments 向您显示泄漏时,它会向您显示泄漏对象的分配位置,但不一定是实际导致泄漏的代码。我怀疑您正在泄漏
myDict
,因此其中的所有对象也都被泄漏。You don't need to release it. Since
stringWithFormat
doesn't start withalloc
,init
,new
,copy
, ormutableCopy
, 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 leaking
myDict
, and thus all the objects inside it are leaked as well.你永远不会释放它。已经自动发布了。
您只能释放通过名称以
+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.