CoreData 中的删除不会删除;重新启动后出现删除的对象

Deletion in CoreData doesn't delete; deleted object appears after relaunching

我从核心数据中删除对象的代码:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // removing from core data
        let managedContext = DataController().managedObjectContext
        managedContext.delete(books[indexPath.row] as NSManagedObject)
        books.remove(at: indexPath.row)
        do {
            try managedContext.save()
// I debug on this step : "po books" and I do see that the book was deleted from the books. even more there is no errors.
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
        // Delete the row from the data source (from table view)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

所以删书后。它从 table 视图中消失,也从书籍(核心数据实体)中删除。

但随后我重新启动该应用程序,已删除的图书将再次出现(因为它之前从未被删除过)。

我找到了这个:link

但不幸的是,由于一些提交等原因,它没有多大意义。我存储在设备本地的核心数据上。

这些代码可能会有所帮助:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let managedContext = DataController().managedObjectContext
    let fetchRequest: NSFetchRequest<Book> = Book.fetchRequest()
    do {
        let results =
            try managedContext.fetch(fetchRequest)
        books = results
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
    booksListTableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: bookCellIdentifier, for: indexPath) as! ShowDataTableViewCell
    let index = (indexPath as NSIndexPath).row
    let book = books[indexPath.row]
    cell.valueLabel.text = book.value(forKey: "bookName") as! String?
    return cell
}

提前致谢!

当您保存托管对象上下文时,它会将其保存到其父上下文中。这并不一定意味着它已保存到磁盘。

要保存到磁盘,您需要保存持久存储。如果您在 Xcode 中创建一个新应用程序并选择 "Use Core Data",您将在应用程序委托中看到在 applicationWillTerminate 中执行此操作的代码。

根据上面的建议,我修改了 AppDelegate,使其与我要添加核心数据的项目相同。 现在效果很好。

谢谢!