2016-09-21 88 views
0

我對象的刪除代碼後會出現: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 
} 

謝謝!

+0

使用默認的初始化工具如DataController()'要小心。您將始終獲得具有不同託管上下文的類的新實例。蘋果建議將Core Data堆棧保留在AppDelegate中(或者至少使用一個單例類)是完美的。 – vadian

+0

我之所以沒有使用AppDelegate是因爲我在創建項目後添加了核心數據。通過添加DataController –

回答

1

保存託管對象上下文時,會將其保存到其父上下文中。這並不一定意味着它被保存到磁盤。

要保存到磁盤,您需要保存持久性存儲。如果您在Xcode中創建新應用程序並選擇「使用核心數據」,您將在應用程序代理中看到代碼,該代碼在applicationWillTerminate中執行此操作。

+0

這是我在創建項目之後添加核心數據的問題,找到了通過添加新類的教程。手動。而不是在創作時刻。謝謝! –

0

根據以上建議,我修改了AppDelegate,使其與我將添加核心數據的項目相同。 現在它運作良好。

謝謝!

相關問題