搜索栏控制器和 NSFetchedResultsController

Posted

技术标签:

【中文标题】搜索栏控制器和 NSFetchedResultsController【英文标题】:Search bar controller and NSFetchedResultsController 【发布时间】:2015-12-02 17:52:10 【问题描述】:

我有一个带有搜索栏控制器的表格和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]
    


我很喜欢这个tutorial。一切正常。但是,如果我在搜索时尝试删除行:

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 的委托 -controllerDidChangeContent:。无效更新:第 0 节中的行数无效。现有节中包含的行数 更新后(3)必须等于包含的行数 更新前的那个部分(3),加减行数 从该部分插入或删除(0 插入,1 删除)和加上 或减去移入或移出该部分的行数(0 移动 入,0 移出)。与 userInfo (null)

当我使用搜索栏控制器时如何编辑元素?

【问题讨论】:

【参考方案1】:

您正在更新由 fetched results 控制器获取的数据集,而不更新表视图。

了解您必须为更改准备表格视图,然后重新加载表格视图,确保您的表格视图数据源方法响应数据集中的更改。

您可能还需要确保您的表格视图委托方法响应更改,具体取决于您的实现。

【讨论】:

以上是关于搜索栏控制器和 NSFetchedResultsController的主要内容,如果未能解决你的问题,请参考以下文章

搜索栏控制器 iOS 11 问题 - 搜索栏和范围按钮重叠

独立的搜索栏和表格视图控制器

搜索控制器中的搜索栏重叠状态栏

视图控制器中的搜索栏和搜索显示控制器,其中包含 UITableView

iOS 7 导航栏中的搜索栏

从搜索控制器导航后缺少导航栏