ios - 使用 fetchedResultsController 删除 TableView 中的行

标签 ios objective-c tableview nsfetchedresultscontroller

在 swype 删除期间(此方法最重要的几行):

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
 if (editingStyle == UITableViewCellEditingStyleDelete)
  {
    Table *deleteRow = [self.fetchedResultsController objectAtIndexPath:indexPath];
    [self.managedObjectContext deleteObject:deleteRow];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  }   
}

删除行时出现此错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 2.
The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

如果我注释最后一行代码 ([tableView deleteRowsAtIndexPaths:...]) 一切正常(但我必须刷新 View 才能看到该行已被删除)。

如何正确地做到这一点......?

编辑: 考虑到我添加的@Kyr Dunenkoff 回复:

- (void)controller:(NSFetchedResultsController*)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath*)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath*)newIndexPath
{
    UITableView *tableV = [self tableView];
    switch(type) {
        case NSFetchedResultsChangeDelete:
            [tableV deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController*)controller
{
    [[self tableView] endUpdates];
}

- (void)controllerWillChangeContent:(NSFetchedResultsController*)controller
{
    [[self tableView] beginUpdates];
}

然而,这并没有改变崩溃和错误。 Atm 它只是导致添加新行不再起作用。

最佳答案

要正确执行此操作,请实现 controller:didChangeObject: 方法,在其中为不同的更改类型创建一个 switch,在 NSFetchedResultsChangeDelete 中插入 case你的 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];。因为当您使用像 NSFetchedResultsController 这样的数据源时,所有更改都必须来自那里,而您的表只反射(reflect)它们。 此外,您可以实现 controller:willChangeContentcontroller:didChangeContent,将 [tableView beginUpdates] 放入 willChange[tableView endUpdates]didChange

关于ios - 使用 fetchedResultsController 删除 TableView 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8974740/

相关文章:

ios - UICollectionView 自定义单元格在我滚动时自动刷新

iphone - 在ios应用程序中实现Zoos的要求

ios - 在iOS中使用JSQMessageViewController无法获得聊天气泡

ios - 如何强制单元格行更新高度

ios - 如何使用 Swift 保存从 tableView 上的文本字段收到的用户答案

objective-c - 哪种数据存储类型是存储从服务器接收的数据的最佳方式?

ios - 常量的 getter 和 setter ?

ios - 如何在 React Native 中从一个文件导出和导入到另一个文件

ios - 展开一个可选值 nil

Swift tableview Cell label change Text by button 标签