即使我在紧密循环中使用NSAutoreleasePool,下面的方法中的下列行导致我得到内存警告并最终崩溃我的应用程序(通过注释掉该行,问题消失了)。任何人都有一个想法,为什么这是这种情况?神秘的内存泄漏 - NSString Autorelease问题
filepath = [docpath stringByAppendingPathComponent:file];
-(void)fileCleanup
{
NSString *documentspath = [AppSession documentsDirectory];
NSString *docpath = [documentspath stringByAppendingPathComponent:@"docs"];
NSFileManager *filemanager = [NSFileManager defaultManager];
NSArray *files = [filemanager subpathsOfDirectoryAtPath:docpath error:NULL];
NSLog(@"fileCleanup");
if(files != nil && [files count] > 0)
{
BOOL deletefile;
NSString *filepath;
NSAutoreleasePool *readPool;
NSString *testfile;
NSString *file;
for(file in files)
{
deletefile = YES;
for (testfile in allFiles) {
readPool = [[NSAutoreleasePool alloc] init];
//line below is causing memory leak!
filepath = [docpath stringByAppendingPathComponent:file];
//if([filepath isEqualToString:testfile])
//{
// deletefile = NO;
// break;
//}
[readPool drain];
}
if(deletefile)
{
[self logText:[@"\nD: " stringByAppendingString:[@"docs/" stringByAppendingPathComponent:file]]];
[filemanager removeItemAtPath:[docpath stringByAppendingPathComponent:file] error:NULL];
}
}
}
您可能已经在内存方面很紧张,所以您提到的这一行可能只是分配剩余的几个字节来达到高位标记的那一行。在外循环中,为了记录目的而创建了大量字符串,直到主循环完成处理当前事件时才会释放它。你的autorelease池无助于此。 – Codo