2011-08-21 65 views
0

即使我在緊密循環中使用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]; 
      } 
     } 
    } 
+2

您可能已經在內存方面很緊張,所以您提到的這一行可能只是分配剩餘的幾個字節來達到高位標記的那一行。在外循環中,爲了記錄目的而創建了大量字符串,直到主循環完成處理當前事件時纔會釋放它。你的autorelease池無助於此。 – Codo

回答

1

我用php in_array()函數的Objective C等價物替換了內部的「for」循環,內存問題消失了!

NSUInteger matchint = [allFiles indexOfObject:[docpath stringByAppendingPathComponent:file]]; 
    if(matchint != NSNotFound) 
     deletefile = NO; 
1

break語句將您從內循環中刪除,而無需在NSAutoreleasePool上調用-drain。

+0

我發現張貼後仍然沒有解決我的問題,當我糾正。 – VinnyD