2015-12-02 53 views
1

我有搜索栏控制器和NSFetchedResultsController表:搜索栏控制器和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: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), 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). with userInfo (null)

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

回答

0

您正在更新由提取结果控制器提取的数据集,而不更新表视图。

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

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

相关问题