我對象的刪除代碼後會出現: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
}
謝謝!
使用默認的初始化工具如DataController()'要小心。您將始終獲得具有不同託管上下文的類的新實例。蘋果建議將Core Data堆棧保留在AppDelegate中(或者至少使用一個單例類)是完美的。 – vadian
我之所以沒有使用AppDelegate是因爲我在創建項目後添加了核心數據。通過添加DataController –