views:

218

answers:

2

Hi everyone

I have a weird memory leak with NSTimeIntervall and NSDate. Here is my code:

NSTimeInterval interval = 60*60*[[[Config alloc] getCacheLifetime] integerValue];
NSDate *maxCacheAge = [[NSDate alloc] initWithTimeIntervalSinceNow:-interval];

if ([date compare:maxCacheAge] == NSOrderedDescending) {
    return YES;
} else {
    return NO;
}

date is just an NSDate object, this should be fine. Instruments tells me that "interval" leaks, yet I do not quite understand this, how can I release a non-object? The function ends after the code snippet I posted here, so from my understanding interval should get automatically deallocated then.

Thanks a lot!

A: 

Found the problem, in case you come across the same issue, this is the solution:

[[ClubzoneConfig alloc] loadConfigFile];
NSTimeInterval interval = 60*60*[[[ClubzoneConfig alloc] getCacheLifetime] integerValue];
NSDate *maxCacheAge = [[NSDate alloc] initWithTimeIntervalSinceNow:-interval];

if ([date compare:maxCacheAge] == NSOrderedDescending) {
    [maxCacheAge release];
    return YES;
} else {
    [maxCacheAge release];
    return NO;
}

The problem is that the maxCacheAge object needs to get released, as I own it (see link below).

I got it thanks to the awesome solution here: http://stackoverflow.com/questions/2078016/iphone-memory-management

Robin
Um, the way you're using `[ClubzoneConfig alloc]` looks wrong. See my answer for more.
benzado
+2  A: 

It is probably telling you that a leak is happening on that line.

The expression [[[Config alloc] getCacheLifetime] integerValue] is your problem.

First of all, you care creating an object (calling alloc) but you lose the reference to it before calling release or autorelease, so it is leaking.

Also, you really ought to call an init method immediately after allocating the object. Even if your Config class doesn't do anything special, NSObject's init method will need to be called.

If you replace that line with

Config *config = [[Config alloc] init];
NSTimeInterval interval = 60*60*[[config getCacheLifetime] integerValue];
[config release];

That leak should be plugged up.

You are also leaking the maxCacheAge object. Inserting [maxCacheAge autorelease]; before the if statement should fix that.

benzado
Hey, thanks for the solution! Now I also understand why the interval leaks. I applied you solution and it seems to work, is probably much better than my idea.
Robin
I would also like to point out that BOTH of these leaks are caught by the static analyzer (Xcode > Build > Build and Analyze) with no need to run Instruments.
gerry3