Search code examples
iphonememory-leaksnstimeinterval

NSTimeInterval memory leak


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!


Solution

  • 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.