如何从TableView中删除特定的核心数据对象

问题描述:

所以我试图从tableView中删除数据,它将删除行中的单元格,但它不会从coreData中删除信息,导致它在再次加载时我打电话给.reloadData()。我对coredata非常陌生,我不知道如何选择我制作的具体Recipe项目。如何从TableView中删除特定的核心数据对象

这里就是我处理删除:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if (editingStyle == UITableViewCellEditingStyle.delete) { 
     // handle delete (by removing the data from your array and updating the tableview) 
     recipes.remove(at: indexPath.row) 
     tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) 

    } 

} 

以下是我正在创建中coreData的项目,如果这有助于。另外,我有一个Git仓库here如果任何人愿意看深

@IBAction func createNewRecipeButton(_ sender: Any) { 
     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 
     let newRecipe = Recipe(context: context) 
     newRecipe.title = recipeTitleTextBox.text 
     newRecipe.instructions = recipeInstructionsTextBox.text 
     newRecipe.time = recipeTimeTextBox.text 
     (UIApplication.shared.delegate as! AppDelegate).saveContext() 
     navigationController!.popToRootViewController(animated: true) 
} 

您当前的去除方法仅仅删除存储阵列的配方。你需要告诉上下文来摆脱它,以及...

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if (editingStyle == UITableViewCellEditingStyle.delete) { 
     let recipe = recipes.remove(at: indexPath.row) 
     tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) 
     guard let moc = recipe.managedObjectContext else { return } 
     moc.delete(recipe) 
     moc.processPendingChanges() 
    } 
} 

您也可能要考虑使用NSFetchedResultsController。有几个教程。