【问题标题】:Deletion in CoreData doesn't delete; deleted object appears after relaunchingCoreData 中的删除不会删除;重新启动后出现已删除的对象
【发布时间】:2016-09-21 17:14:42
【问题描述】:

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

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)
    }
}

所以删除这本书后。它从表视图中消失,并且从书籍(核心数据实体)中删除。

然后我重新启动应用程序,被删除的书会再次出现(因为它以前从未被删除过)。

我发现了这个: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
}

提前致谢!

【问题讨论】:

  • 小心使用默认初始化器,例如DataController()。您将始终获得具有不同托管上下文的类的新实例。 Apple 建议将 Core Data 堆栈保留在 AppDelegate 中(或至少使用单例类)是完全有道理的。
  • 我没有使用 AppDelegate 的原因是我在创建项目后添加了核心数据。通过添加新类 DataController 找到了教程

标签: ios swift core-data swift3 ios10


【解决方案1】:

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

要保存到磁盘,您需要保存持久存储。如果您在 Xcode 中创建一个新应用程序并选择“使用核心数据”,您将在应用程序委托中看到在 applicationWillTerminate 中执行此操作的代码。

【讨论】:

  • 这是我创建项目后添加核心数据的问题。手动。不是在创作的那一刻。谢谢!
【解决方案2】:

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

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多