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 } }
额外检查点
- 确认
card?.gratefuls在保存和加载时的逻辑一致,确保加载后数组长度稳定为4 - 验证UITableView的
numberOfRowsInSection方法返回值为9,保证行数量与界面需求匹配
内容的提问来源于stack exchange,提问作者za.ch
相关产品推荐
相关产品推荐

