CoreData中的删除不会删除;删除的对象从核心数据重新推出
问题描述:
我对象的删除代码后会出现:CoreData中的删除不会删除;删除的对象从核心数据重新推出
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
}
谢谢!
答
保存托管对象上下文时,会将其保存到其父上下文中。这并不一定意味着它被保存到磁盘。
要保存到磁盘,您需要保存持久性存储。如果您在Xcode中创建新应用程序并选择“使用核心数据”,您将在应用程序代理中看到代码,该代码在applicationWillTerminate
中执行此操作。
+0
这是我在创建项目之后添加核心数据的问题,找到了通过添加新类的教程。手动。而不是在创作时刻。谢谢! –
答
根据以上建议,我修改了AppDelegate,使其与我将添加核心数据的项目相同。 现在它运作良好。
谢谢!
使用默认的初始化工具如DataController()'要小心。您将始终获得具有不同托管上下文的类的新实例。苹果建议将Core Data堆栈保留在AppDelegate中(或者至少使用一个单例类)是完美的。 – vadian
我之所以没有使用AppDelegate是因为我在创建项目后添加了核心数据。通过添加DataController –