n.evermind
n.evermind

Reputation: 12004

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!

Upvotes: 0

Views: 190

Answers (2)

Constantino Tsarouhas
Constantino Tsarouhas

Reputation: 6886

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.

Upvotes: 1

markrickert
markrickert

Reputation: 647

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.

Upvotes: 2

Related Questions