2012-07-05 303 views
1

分析是顯示內存泄漏其中I在下面的代碼段分配文件路徑值FILEB:內存泄漏:

NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; 

NSString *filePath = [docsDir stringByAppendingPathComponent:@"/fileA"]; 

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ 
    self.propertyA = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; 
} else { 
    // initialize array with default values and write to data file fileA 
    [self populatePropertyAForFile:filePath];  
} 

filePath = [docsDir stringByAppendingPathComponent:@"/fileB"]; 

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ 
    self.propertyB = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; 
} else { 
    // initialize array with default values and write to data file fileB 

    [self populatePropertyBForFile:filePath]; 

} 

我明白這是因爲(爲的fileA)的前一個值還沒有被釋放。但我無法弄清楚如何阻止這種泄漏。

+0

有些事情你不告訴我們。 – 2012-07-05 15:37:13

回答

2

沒有。filePath沒有問題。問題幾乎可以肯定與您的兩個屬性propertyApropertyB。如果它們是保留屬性,那麼分配給它們的數組及其內容將會泄漏,因爲您擁有您分配的數組,並且您沒有釋放它們。改變這樣的行:

self.propertyA = [[[NSMutableArray alloc] initWithContentsOfFile:filePath] autorelease]; 
                     // ^^^^^^^^^^^ will release ownership of the array 
+0

打我吧.... :( – trojanfoe 2012-07-05 15:39:45

+0

hm ..是的,我的錯爲不放autorelease。謝謝指出它。也忘了Xcode不指向內存泄漏的地方,而是內存泄漏的對象分配。 – pm08 2012-07-05 16:00:04