You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中TableView实现CRUD操作遇到索引路径无效错误如何解决

崩溃原因

你声明的全局索引变量var index = IndexPath()是无参数初始化的空索引路径,不包含UITableView要求的section和row两个参数。只要在未点击任何表格行的情况下触发了输入框编辑事件,空的索引路径就会被传入tableView.cellForRow(at:)方法,触发系统校验抛出崩溃。

修复方案

  • 第一步:修改全局索引变量的定义,改为可选类型规避空值调用
    把原有代码里的
var index = IndexPath()

替换为

var selectedIndexPath: IndexPath?
  • 第二步:修改行选中的赋值逻辑,同步修改输入框编辑的校验逻辑
    首先替换didSelectRowAt代理方法的内容:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedIndexPath = indexPath
    self.txtfield.text = models[indexPath.row]
}

再替换textFieldEdit点击事件的内容,先校验索引有效性再执行逻辑,同时同步修改数据源避免后续刷新数据回滚:

@IBAction func textFieldEdit(_ sender: UITextField) {
    guard let inputText = sender.text, !inputText.isEmpty, let selectPath = selectedIndexPath else { return }
    // 先更新数据源
    models[selectPath.row] = inputText
    if let cell = tableView.cellForRow(at: selectPath) {
        cell.textLabel?.text = inputText
    }
}
  • 第三步(可选优化):删除行时同步清空无效选中状态,避免后续调用残留的无效索引
    修改删除行的代理方法,新增选中状态清空逻辑:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete{
        // 新增逻辑:删除的是当前选中行时清空选中状态
        if indexPath == selectedIndexPath {
            selectedIndexPath = nil
            txtfield.text = ""
        }
        tableView.beginUpdates()
        models.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        tableView.endUpdates()
    }
}

内容的提问来源于stack exchange,提问作者Jestin Saji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:54:00