문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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: iPhone Memory Management

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top