所以我试图从 tableView
中删除数据,它会删除行中的单元格,但不会删除 coreData 中的信息,导致它在我重新加载时再次加载调用 .reloadData()
。我是 coredata 的新手,我不知道如何选择我制作的特定 Recipe
项目。
这是我处理删除的地方:
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
。周围有几个教程。
关于swift - 如何从 TableView 中删除特定的 coreData 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46850813/