【问题标题】:tableView.deleteRows(at:with:) crashed every timetableView.deleteRows(at:with:) 每次都崩溃
【发布时间】:2017-04-21 08:39:57
【问题描述】:

当我试图删除从 Core Data 的 NSManagedObject 派生的 Product 类型的对象时。对象可以成功移除。但它在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/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit -3600.7.47/UITableView.m:1737

【问题讨论】:

    标签: swift uitableview core-data


    【解决方案1】:

    您忘记从数组中删除对象。在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.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2015-12-29
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多