[英]NSString alloc outside autorelease pool creates mysterious memory leak?
[英]Mysterious Memory Leak - NSString Autorelease Issue
即使我在緊密循環中使用NSAutoreleasePool,下面方法中的以下行導致我獲取內存警告並最終崩潰我的應用程序(通過注釋掉該行,問題消失)。 任何人都知道為什么會這樣?
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];
}
}
}
我用php in_array()函數的Objective C等效替換了內部的“for”循環,內存問題消失了!
NSUInteger matchint = [allFiles indexOfObject:[docpath stringByAppendingPathComponent:file]];
if(matchint != NSNotFound)
deletefile = NO;
break語句讓你退出你的內部for循環而不在NSAutoreleasePool上調用-drain。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.