在numberOfRowsInSection中调用TableView BeginUpdates

时间:2012-12-14 23:30:45

标签: objective-c ios uitableview nsfetchedresultscontroller

我有一个由NSFectchedResultsController支持的tableview,当我没有来自FRC的结果时,我正试图显示一个自定义单元格。我遇到的问题是BeginUpdates回忆起numberOfRowsInSection。我想保持tableview活动(而不是仅仅在其位置显示图像),以便用户可以执行拉动刷新。

代码:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.fetchedResultsController.fetchedObjects count] == 0) {
    if (!specialCellShowing) {
        specialCellShowing = TRUE;
        [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
    }
    return 1;
}
else {
    if (specialCellShowing) {
        specialCellShowing = FALSE;
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
    }
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    return [self.fetchedResultsController.fetchedObjects count];
}

}

问题是返回1;声明。发生的事情是第一次调用numberOfRowsInSection时它设置了specialCellShowing = TRUE并点击开始更新,它会调用numberOfRowsInSection。方法的begin updates实例看到specialCellShowing为true并返回1并退出。现在进行插入调用,然后在endUpdates上发生崩溃,因为tableview认为表中有1个单元,插入了1个单元,以前有1个单元。另一个问题是我需要返回1,因为在后续的numberOfRowsInSection调用中,我希望它不会弄乱表,只返回说我有一个自定义单元格。

我想我想知道的是,是否有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:1)

当tableview更新其显示时,您无法改变tableview。除非您正在改变tableview,否则不需要调用deleteRowsAtIndex路径。您需要有一个单独的方法:一个响应事件并改变tableview的数据(并且可能调用begin / endUpdates并添加或删除行)。 -numberOfRowsInSection应该只检查后备数据并返回一个答案。 tableview正在进行全面更新,因此无论如何在tableview中添加和删除行都是无用的。

相关问题