2010-09-03 73 views
0

我試圖從我的代碼中刪除內存泄漏有一些麻煩。在下面的代碼中,我得到了一行內存泄漏「configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain];」但是,當我刪除保留,應用程序崩潰,並將保留更改爲autorelease也會導致崩潰。內存泄漏與陣列 - 目標c

感謝, 威廉

-(NSArray*)decodeConfigurationFile:(NSString*)fileName{ 
NSArray* configurationArray = [[NSArray alloc] init]; 

NSString *controllerConfigurationFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"]; 
if (controllerConfigurationFilePath != nil) { 
    // returns array of items storing the data for form 
    configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain]; 
} 

// returns fields dictionary objects from plist into an array 
return [[configurationArray objectAtIndex:0] objectForKey:@"fields"]; 
} 

回答

2

的問題似乎是,你正在做

NSArray* configurationArray = [[NSArray alloc] init]; 

分配數組,然後你做

創建新陣列
configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain]; 

沒有發佈您創建的第一個數組。第一行應該只是

NSArray* configurationArray = nil; 

,你不應該需要保留,因爲它是一個局部變量,你不保持一個指向超出函數的範圍數組。

崩潰可能來自這樣一個事實,即調用此方法的對象可能不會保留此方法返回的對象,如果沒有其他任何內容保留它,它將與數組一起釋放。所以當你試圖在你的代碼的其他地方訪問這個對象時,這個對象就不在那裏了。 如果調用對象需要保留這個返回的對象,調用對象應該保留返回的對象。

+0

感謝您的快速回復。我實現了上述更改。並確保返回的數組分配給的變量(「字段」)具有保留。然而,在我的代碼中,這個變量被擦除,當我嘗試使用它時,它崩潰了。我認爲這可能與不保留這個「[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath]」然後試圖用這個語句來使用它:「[[field objectAtIndex:index] objectForKey:@」costAtHour「];」 – williamb 2010-09-03 15:45:23

+0

進一步調查,顯示我在訪問該屬性時未使用self.fields,這是導致崩潰的原因。 謝謝 – williamb 2010-09-03 15:59:28

+0

它可能有助於查看調用隱含的'fields'字典的.plist條目。 – falconcreek 2010-09-03 16:08:31