当前位置: 动力学知识库 > 问答 > 编程问答 >

iphone - I'm leaking a few bytes -- why?

问题描述:

Sorry for the very unspecific title, but I'm just debugging my programme with LEAKS and I found a leak in the following few lines of code:

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; // LEAKS shows 80%

[dateFormat setDateFormat:@"EEE-dd-MMMM-yyyy"];

NSDate *today = [[NSDate alloc] init]; // LEAKS shows 20%

NSString *theDate = [dateFormat stringFromDate:today];

[noteBookContent replaceObjectAtIndex:(currentPageCounter*3)+1 withObject:theDate];

[dateFormat release];

[today release];

LEAKS tells me that one line is 80% leaking, the other 20%. But why? I am releasing both...

It's only 16 bytes, so I guess I shouldn't worry... or should I worry about this kind of stuff? Anyway, it's bugging me that I don't understand why my code is leaking, so any help would be very much appreciated. Thanks!

Also, while we are on the topic of LEAKS -- there are also a couple of other Leaked Blocks in my programme such as 'Malloc 32 Bytes Foundation -[NSCFString appendString:]' ... LEAKS does not give me any reference to my code where this is supposed to be leaking. How am I to find out where this memory is leaking, then?

Sorry if this is all basic stuff, but as you can probably gather, this is the first time I'm using LEAKS.

Thanks in advance!

网友答案:

I'd change your methodology if you're releasing the objects right away and aren't performing more actions with them. Try this approach using auroreleased objects:

NSString *theDate = [NSDateFormatter localizedStringFromDate:[NSDate date] 
                                                   dateStyle:@"EEE-dd-MMMM-yyyy" 
                                                   timeStyle:nil];
[noteBookContent replaceObjectAtIndex:(currentPageCounter*3)+1 
                            withObject:theDate];

*note, I haven't checked this code for accuracy or leaks, but it should do exactly the same thing.

网友答案:

Try to use autoreleased initializers. For example, instead of using

date = [[NSDate alloc] init];

use

date = [NSDate date];

and so forth.

When I use autoreleased initializers, I don't get leak messages.

网友答案:

I guess you should release theDate also?

分享给朋友:
您可能感兴趣的文章:
随机阅读: