【问题标题】:How to delete specific coreData object from TableView如何从 TableView 中删除特定的 coreData 对象
【发布时间】:2017-10-20 14:03:27
【问题描述】:

所以我试图从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)
}

【问题讨论】:

    标签: swift uitableview core-data


    【解决方案1】:

    您当前的删除方法只是从存储阵列中删除配方。您还需要告诉上下文以摆脱它......

    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。周围有几个教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多