tableView.deleteRows(at:with :)每次都崩溃

时间:2017-04-21 08:39:58

标签: swift uitableview core-data

当我尝试删除从Product核心数据派生的NSManagedObject类型的对象时。该对象可以成功删除。但它在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-04-21 15:54:42.159 POS [20241:2852960] ***断言失败 - [UITableView _endCellAnimationsWithContext:],/ BuildRoot / Library / Cache / com.apple.xbs / Source / UIKit_Sim / UIKit -3600.7.47 / UITableView.m:1737

1 个答案:

答案 0 :(得分:4)

您忘记从数组中删除对象了。在remove(at:)上使用productsInSection并从数组中删除对象,然后调用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.
    }
}
相关问题