【发布时间】: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