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 w开发者_运维问答ay 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?
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.
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.
精彩评论