即使我在緊密循環中使用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