2011-05-04 36 views
0

我正在將數據從plist加載到我的應用程序中的tableview中。數據存儲在可變字典的可變字典中。 這裏是我的viewDidLoad方法:從表格視圖刪除行時發生內存泄漏

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.title = @"Categories"; 

    // load data from plist fle 
    self.categories = [[[NSMutableDictionary alloc] initWithContentsOfFile: 
            [[NSBundle mainBundle] pathForResource:@"InventoryItems" ofType:@"plist"]] autorelease]; 

    // add buttons to navigation menu 
    self.navigationItem.rightBarButtonItem = self.editButtonItem; 
    self.navigationItem.leftBarButtonItem = self.addButton; 
} 

我的tableview是可編輯的,所以用戶可以刪除類別。在我commitEditingStyle:forRowAtIndexPath:方法更新我的數據模型:

[self.categories removeObjectForKey: [[self.categories allKeys] objectAtIndex:indexPath.row]]; 

當我分析我的程序的時候,出現內存泄漏。我不擅長使用配置文件工具,但似乎每次刪除一行時都會在我的類別字典中發現泄漏。

我想知道我錯過了什麼發佈?這是一個問題,我正在刪除的對象也是一個字典,我也需要刪除它的對象?

回答

3

此泄漏(如果該屬性是保留或複印件):

self.categories = [[NSMutableDictionary alloc] initWithContentsOfFile: 
            [[NSBundle mainBundle] pathForResource:@"InventoryItems" ofType:@"plist"]]; 

用這個代替:

categories = [[NSMutableDictionary alloc] initWithContentsOfFile: 
            [[NSBundle mainBundle] pathForResource:@"InventoryItems" ofType:@"plist"]]; 

或本:

self.categories = [[[NSMutableDictionary alloc] initWithContentsOfFile: 
            [[NSBundle mainBundle] pathForResource:@"InventoryItems" ofType:@"plist"]] autorelease]; 
+1

泄漏背後的原因是init創建的保留計數爲1,並且屬性上的保留也創建保留計數爲1,只在您預期時給予保留計數2。 。 – 2011-05-04 20:54:04

+0

感謝您的快速回答!我爲self.categories添加了autorelease,但仍然有同樣的問題。泄漏的對象包括:_NSCFDictionary和NSCFString。 – lanan 2011-05-04 21:00:18

+0

@Shvetusya你已經向我們展示瞭如何創建你的字典以及如何從中刪除對象,但是在兩者之間必須使用這些對象來在你的表格視圖中顯示數據。也許你過度保留這些對象(只是猜測)。 – albertamg 2011-05-04 22:44:18

0

我不知道這是否會放棄你有什麼不同?

NSMutableDictionary *d = [[NSMutableDictionary alloc] initWithContentsOfFile: 
            [[NSBundle mainBundle] pathForResource:@"InventoryItems" ofType:@"plist"]]; 

self.categories = d; 
[d release];