如果我释放传递给insertSections的NSIndexSet参数,为什么会崩溃:withRowAnimation:

时间:2012-02-06 15:25:04

标签: iphone cocoa-touch

我已经编写了一些代码来批量删除/从表格视图中插入部分和单元格。但我遇到了一个我无法理解的问题。我的代码如下

NSMutableArray *deleteIndexPaths = [[NSMutableArray alloc] initWithCapacity:1];
NSMutableArray *insertIndexPaths = [[NSMutableArray alloc] initWithCapacity:1];
NSIndexSet *insertSections = [[NSIndexSet alloc] initWithIndex:kDeleteSection];
NSArray *insertDeleteIndexPaths = [[NSArray alloc] initWithObjects:[NSIndexPath indexPathForRow:0 inSection:kDeleteSection], nil];

/// init deleteIndexPaths and insertIndexPaths

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationRight];
[self.tableView insertSections:insertSections withRowAnimation:UITableViewRowAnimationRight];
[self.tableView insertRowsAtIndexPaths:insertDeleteIndexPaths withRowAnimation:UITableViewRowAnimationRight];
[self.tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

[insertSections release];
[deleteIndexPaths release];
//[insertSections release]; // If uncommented it, program will crash.
[insertDeleteIndexPaths release];

作为对代码的评论,如果我取消注释语句 [insertSections release]; ,程序将崩溃。为什么?我找不到答案。

2 个答案:

答案 0 :(得分:3)

因为你要发布两次:

**[insertSections release];**
[deleteIndexPaths release];
**//[insertSections release]; // If uncommented it, program will crash.**

答案 1 :(得分:1)

我将使用快速简单的答案,根据提供的代码,您将创建一个过度释放的情况。当您在顶部的+alloc处致电NSIndexSet时,您隐含地声明所有权并需要抵消-release来电。在提供的示例中,注释掉的-release调用是第二个,并导致将消息发送到已解除分配的实例。