【问题标题】:NXException when removing and then adding an itme to UITableView删除然后将项目添加到 UITableView 时出现异常
【发布时间】:2020-01-24 02:00:38
【问题描述】:

当我从列表中删除一个对象并尝试在其中添加一个新对象时,我收到此错误

2020-01-24 14:40:26.692343+1300 HappyDays[25416:1017241] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

我看到了与此类似的其他问题,但我已尝试实施这些解决方案。 (Similar issue,another similar issue)

我的代码部分: 从表格中选择要删除的单元格

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {      
    activeObjectives.actives.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .left)
}

通过点击按钮将新对象添加到表格中

@IBAction func getGoals(_ sender: UIButton) {

    let newRowIndex = activeObjectives.actives.count
    activeObjectives.setRandomGoalToActive(allObjectiveList: allGoalsArray)

    addActiveGoalToactiveObjectives()

    let indexPath = IndexPath(row: newRowIndex, section: 0)
    let indexPaths = [indexPath]
    activeGoalDisplay.insertRows(at: indexPaths, with: .automatic)

}

如果还需要它,这是我在上面调用的 addActiveGoalToactiveObjectives 函数

func addActiveGoalToactiveObjectives() {
    for goal in allGoalsArray.goalsList {
        if goal.isActive == true && activeObjectives.actives.contains(goal) == false {
            activeObjectives.actives.append(goal)
        }
    }
}

在此先感谢,非常感谢任何帮助

【问题讨论】:

  • numberOfRowsInSection如何计算?
  • 如果addActiveGoalToactiveObjectives中没有添加对象(或多个对象),代码会崩溃。
  • 我是通过获取activeObjects数组// Set the number of rows to the amount of goals in the activeObjectives array func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return activeObjectives.actives.count }中的数字来计算的

标签: ios swift uitableview


【解决方案1】:

我发现了问题。从列表中删除对象时,我没有将对象值设置为 false。现在,当我删除它们时,我将对象设置为非活动状态。

        activeObjectives.actives[indexPath.row].setInactive()
        activeObjectives.actives.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .left) 
    }```


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多