1

我有一个奇怪的 NSTimeIntervall 和 NSDate 内存泄漏。这是我的代码:

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 只是一个 NSDate 对象,这应该没问题。仪器告诉我“间隔”泄漏,但我不太明白,我怎样才能释放一个非对象?该函数在我在此处发布的代码片段之后结束,因此根据我的理解间隔应该会自动解除分配。

非常感谢!

4

2 回答 2

4

它可能会告诉您该线路上发生了泄漏。

表达[[[Config alloc] getCacheLifetime] integerValue]是你的问题。

首先,您关心创建一个对象(调用),但在调用oralloc之前丢失了对它的引用,因此它正在泄漏。releaseautorelease

init此外,您确实应该在分配对象后立即调用方法。即使您的Config班级没有做任何特别的事情,也需要调用NSObject'方法。init

如果您将该行替换为

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

应该堵住那个漏水的地方。

您也在泄漏maxCacheAge对象。在 if 语句之前插入[maxCacheAge autorelease];应该可以解决这个问题。

于 2010-01-16T20:51:52.193 回答
0

找到问题了,如果你遇到同样的问题,这是解决方案:

[[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;
}

问题是 maxCacheAge 对象需要被释放,因为我拥有它(见下面的链接)。

多亏了这里很棒的解决方案:iPhone 内存管理

于 2010-01-16T20:51:16.547 回答