我有一个带有搜索栏控制器的表,并且NSFetchedResultsController

class CartViewController: UIViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
        self.tableView.beginUpdates()
    }

    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

        switch type {
            case .Insert:
                if let _newIndexPath = newIndexPath {
                    tableView.insertRowsAtIndexPaths([_newIndexPath], withRowAnimation: .Fade)
                }
            case .Delete:
                if let _indexPath = indexPath {
                    tableView.deleteRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade)
                }
            case .Update:
                if let _indexPath = indexPath {
                    tableView.reloadRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade)
                }
            default:
                self.tableView.reloadData()
        }

        self.products = controller.fetchedObjects as! [Product]
    }

}

我真的很喜欢这个。一切正常。但如果我在搜索时尝试删除行:
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

        let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete",handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

                    let product = (self.searchController.active) ? self.searchResults[indexPath.row]:self.products[indexPath.row]
                    product.setValue(false, forKey: "inCart")
                    do {
                        try self.appDelegate.managedObjectContext.save()
                    } catch {
                        fatalError("Failure to save context: \(error)")
                    }

            })
}

我收到错误:
CoreData:错误:严重的应用程序错误。捕获到异常
从NSFetchedResultsController的委托调用
-控制器IDChangeContent:。无效更新:第0节中的行数无效。现有区段中包含的行数
更新后(3)必须等于
更新(3)之前的部分,加上或减去行数
从该节中插入或删除(0已插入,1已删除)以及
或减去移入或移出该节的行数(0
在中,0移出)。带用户信息(空)
如何在使用搜索栏控制器时编辑元素?

最佳答案

您正在更新由获取的结果控制器获取的数据集,而不更新表视图。
了解必须为更改准备表视图,然后重新加载表视图,确保表视图数据源方法响应数据集中的更改。
您可能还需要确保表视图委托方法响应更改,具体取决于您的实现。

关于ios - 搜索栏 Controller 和NSFetchedResultsController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34049629/

10-12 00:15
查看更多