2011-05-04 38 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];