swift - 如何从 TableView 中删除特定的 coreData 对象

标签 swift uitableview core-data

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

相关文章:

json - swift UITableView : How to Load data from JSON

iphone - 保存上下文中的 CoreData 错误,NSPersistentStoreCoordinator 没有持久存储

ios - 核心数据错误

ios - Firebase iOS 用户身份验证 : avoiding getting logged out of app

swift - 类层次结构 - 类只能由另一个类调用

iOS 2 UITableViews 并更改隐藏属性或 1 并更改源

ios - 如何在表格 View 单元格中使用开关?

iphone - 动态更改单元格高度时 UITableView 的不自然 SCSS

cocoa - 使用 iOS 5 和 RestKit 设置 CoreData 应用程序的正确方法是什么

ios - Swift 中使用 SKSpriteNode 进行水平无限滚动