2017-04-21 2 views
1

Als ich versuchte, ein Objekt vom Typ , das von NSManagedObject von Core Data abgeleitet wurde, zu entfernen. Das Objekt kann erfolgreich entfernt werden. aber es stürzte auf der Linie tableView.deleteRows(at:with:).tableView.deleteRows (at: with :) stürzte jedes Mal ab

Also, jedes Mal, wenn es abgestürzt ist, öffne ich die App erneut, das Objekt wurde erfolgreich entfernt, aber ich weiß nur nicht, warum es in tableView.deleteRows(at:with:) abgestürzt ist.

Wie kann ich es beheben?

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. 
    } 
} 

folgende ist die Fehlermeldung:

2017-04-21 15: 54: 42,159 POS [20241: 2.852.960] *** Assertionsfehler in - [UITableView _endCellAnimationsWithContext:]/BuildRoot/Library/Caches/com.apple.xbs/Quellen/UIKit_Sim/UIKit-3600.7.47/UITableView.m: 1737

Antwort

4

Sie haben vergessen Objekt von Array zu entfernen. Verwenden Sie remove(at:) on productsInSection und entfernen Sie das Objekt aus dem Array und rufen Sie dann 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

danke. Ich bin so dumm. –

Verwandte Themen