2017-04-21 311 views
1

當我試圖從Core Data的NSManagedObject中刪除Product類型的對象時。該對象可以成功刪除。但它在tableView.deleteRows(at:with:)的行上墜毀。tableView.deleteRows(at:with :)每次都崩潰

所以,每當它崩潰,我再次打開應用程序,該對象被成功刪除,但我不知道它爲什麼墜毀在tableView.deleteRows(at:with:)

我該如何解決?

class ProductListInSection { 
    let sectionName: String 
    var productsInSection: [Product] 

    init?(sectionName: String, productInSection: [Product]){ 
     guard !sectionName.isEmpty else { 
      return nil 
     } 
     self.sectionName = sectionName 
     self.productsInSection = productInSection 
    } 
} 


var categorySections: [ProductListInSection] 

// ... 

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == UITableViewCellEditingStyle.delete { 
     let element = self.categorySections[indexPath.section].productsInSection[indexPath.row] 
     AppDelegate.viewContext.delete(element) 
     do { 
      try AppDelegate.viewContext.save() // successfully removed. 
     } catch { 
      print("Fail: \(error)") 
      return 
     } 
     tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) // crashed here. 
    } 
} 

以下是錯誤消息:

2017年4月21日15:54:42.159 POS [20241:2852960] ***在聲明失敗 - [UITableView的_endCellAnimationsWithContext:],/ BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:1737

回答

4

您忘了從數組中刪除對象。在productsInSection上使用remove(at:)並從陣列中移除對象,然後致電deleteRows(at:with:)

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == UITableViewCellEditingStyle.delete { 
     let element = self.categorySections[indexPath.section].productsInSection[indexPath.row] 
     AppDelegate.viewContext.delete(element) 
     do { 
      try AppDelegate.viewContext.save() // successfully removed. 
     } catch { 
      print("Fail: \(error)") 
      return 
     } 
     //Remove the object from array 
     self.categorySections[indexPath.section].productsInSection.remove(at: indexPath.row) 
     tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) // crashed here. 
    } 
} 
+0

謝謝。我很無聊。 –