2015-12-02 82 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

您正在更新由提取結果控制器提取的數據集,而不更新表視圖。

瞭解您必須爲更改準備表視圖,然後重新加載表視圖,確保您的表視圖數據源方法響應數據集中的更改。

您可能還需要確保您的表視圖委託方法響應更改,具體取決於您的實現。

相關問題