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

UITableView的cellForRowAt方法出现Index out of range致命错误求助

问题分析

崩溃核心原因是感恩项的数组索引计算错误,导致访问数组时超出边界:
你的界面仅包含4个感恩项,对应card?.gratefuls数组的有效索引范围是0-3,但代码中直接用indexPath.row(值为5、6、7、8)作为数组下标取值。当重新打开页面加载已保存数据时,gratefuls数组长度固定为4,此时indexPath.row=5时尝试访问gratefuls[5],必然触发Index out of range错误。

修复方案

修改感恩项的索引计算逻辑,将indexPath.row转换为gratefuls数组的合法下标,同时增加边界安全判断:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row < 5 {
        let cell: TaskCell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
        let taskIndex = indexPath.row
        print(taskIndex)

        if let task = card?.tasks[taskIndex] {
            cell.taskText.text = task.text
            cell.taskBtn.isSelected = task.complete
        }

        cell.selectionStyle = .none
        return cell
    } else {
        let cell: GratefulCell = tableView.dequeueReusableCell(withIdentifier: "GratefulCell", for: indexPath) as! GratefulCell
        let gratefulRow = indexPath.row
        print(gratefulRow)
        cell.gratefulNum.text = String(gratefulRow - 4)
        
        // 计算gratefuls数组的合法下标:跳过前5个任务项
        let gratefulIndex = gratefulRow - 5
        // 增加安全校验,避免数组为空或下标越界
        if let gratefuls = card?.gratefuls, gratefulIndex >= 0, gratefulIndex < gratefuls.count {
            cell.gratefulText.text = gratefuls[gratefulIndex].text
        } else {
            cell.gratefulText.text = ""
        }

        cell.selectionStyle = .none
        return cell
    }
}
额外检查点
  1. 确认card?.gratefuls在保存和加载时的逻辑一致,确保加载后数组长度稳定为4
  2. 验证UITableView的numberOfRowsInSection方法返回值为9,保证行数量与界面需求匹配

内容的提问来源于stack exchange,提问作者za.ch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:24:15