Swift - 崩溃在tableView.deleteRows上(at:[selectedIndexPath],带:.automatic)

时间:2018-02-06 07:26:12

标签: ios swift tableview

如何在尝试从tableview中删除单元格时修复此崩溃?

调试器显示该行的错误: tableView.deleteRows(at:[selectedIndexPath],with:。automatic)

有了这条消息: * 2018-02-05 23:13:42.355696-0800发票[66511:19435120] ***断言失败 - [UITableView _endCellAnimationsWithContext:],/ BuildRoot / Library / Cache / com.apple.xbs / Source / UIKit_Sim / UIKit -3698.33.6 / UITableView.m:2011 *

从返回json的服务器加载数据。添加,加载和更新工作正常。

@IBAction func unwindToClients(sender: UIStoryboardSegue) {

    if let sourceViewController = sender.source as? ClientViewController,
        let client = sourceViewController.client,
        let wasDeleted = sourceViewController.wasDeleted {

        if(wasDeleted) {
            if let selectedIndexPath = tableView.indexPathForSelectedRow {
                print("Delteted")
                tableArray.remove(at: selectedIndexPath.row)
                tableView.deleteRows(at: [selectedIndexPath], with: .automatic)
            }

        }
        else {
            if let selectedIndexPath = tableView.indexPathForSelectedRow {
                // Update an existing client.
                tableArray[selectedIndexPath.row] = client
                tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
            }
            else {
                // Add a client.
                tableArray.append(client)

            }
        }

        prepareData()

        DispatchQueue.main.async {
            self.tableView.reloadData()
        }

    }
}

函数prepareData()对数组进行排序并获取索引(A,B,C ...)

//sorts and makes the index
func prepareData() {
    let firstLetters = self.tableArray.map { $0.nameFirstLetter }
    let uniqueFirstLetters = Array(Set(firstLetters))

    self.sortedFirstLetters = uniqueFirstLetters.sorted()
    self.sections = self.sortedFirstLetters.map { firstLetter in
        return self.tableArray
            .filter { $0.nameFirstLetter == firstLetter }
            .sorted { $0.name < $1.name }
    }
}

2 个答案:

答案 0 :(得分:0)

beginUpdates()endUpdates()之间执行删除操作。

例如:

tableView.beginUpdates()
tableView.deleteRows(at: [selectedIndexPath], with: .automatic)
tableView.endUpdates()

答案 1 :(得分:0)

确保在使用deleteRowsinsertRows

时更新您的dataSource