我和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对象,这应该没问题。仪器告诉我“间隔”泄漏,但我不太理解这一点,我如何释放一个非对象?这个函数在我在这里发布的代码片段之后结束,所以根据我的理解,interval应该会自动释放。
非常感谢!
发布于 2010-01-17 04:51:52
它可能会告诉您该线路上正在发生泄漏。
表达式[[[Config alloc] getCacheLifetime] integerValue]是您的问题所在。
首先,您关心创建一个对象(调用alloc),但是在调用release或autorelease之前丢失了对它的引用,所以它是泄漏的。
此外,您确实应该在分配对象后立即调用init方法。即使您的Config类没有做任何特殊的事情,也需要调用NSObject的init方法。
如果将该行替换为
Config *config = [[Config alloc] init];
NSTimeInterval interval = 60*60*[[config getCacheLifetime] integerValue];
[config release];这个漏洞应该被堵住。
您还会泄漏maxCacheAge对象。在if语句之前插入[maxCacheAge autorelease];应该可以解决这个问题。
发布于 2010-01-17 04:51:17
找到问题了,如果你遇到同样的问题,这是解决方案:
[[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 Memory Management
https://stackoverflow.com/questions/2078791
复制相似问题