删除 UITableView 中的最后一个单元格时索引超出范围

Posted

技术标签:

【中文标题】删除 UITableView 中的最后一个单元格时索引超出范围【英文标题】:Index out of range when delete last cell in UITableView 【发布时间】:2018-10-25 08:41:56 【问题描述】:

我试图删除 TableView 中的单元格,在删除最后一个单元格之前一切正常,但出现错误:“线程 1:致命错误:索引超出范围”。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) 
    guard editingStyle == .delete else return
    classList.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .fade)
    let subject = classList[indexPath.row]
    PersistenceService.context.delete(subject)
    PersistenceService.saveContext()

    let fetchRequest: NSFetchRequest<Class> = Class.fetchRequest()
    do 
        let classList = try PersistenceService.context.fetch(fetchRequest)
        self.classList = classList
     catch 
    self.tableView.reloadData()
    print("Delete \(subject)")

然后我尝试让subject = classList[indexPath.row-1],这将解决删除最后一个单元格的错误,但它导致另一个错误是当我尝试删除TableView的第一个单元格时。请帮我修复这个错误,谢谢。

【问题讨论】:

【参考方案1】:

classList 中删除对象后,项目的数量发生了变化,因此后来classList[indexPath.row] 崩溃,因为索引不再存在。

你必须改变顺序

let subject = classList[indexPath.row]
classList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
PersistenceService.context.delete(subject)
PersistenceService.saveContext()

并删除此代码:

let fetchRequest: NSFetchRequest<Class> = Class.fetchRequest()
do 
    let classList = try PersistenceService.context.fetch(fetchRequest)
    self.classList = classList
 catch 
self.tableView.reloadData()

没意义,不需要重新取数据。

【讨论】:

【参考方案2】:

问题是您从classList 中删除了一个项目,然后尝试访问它。

classList.remove(at: indexPath.row)
...
let subject = classList[indexPath.row]

let subject = classList[indexPath.row]移到删除行的代码上方

【讨论】:

以上是关于删除 UITableView 中的最后一个单元格时索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章

删除和插入具有不同高度的单元格时,UITableView 动画故障

iOS 7 UITableView 问题 - 当我们已经有一个单元格时尝试设置滑动以删除单元格

如何滚动到 UITableView 或 UICollectionView 中的最后一个单元格之外

当在 UITableView(在另一个笔尖/视图上)上按下单元格时,如何导航到笔尖(视图)?

如何编写 UI 测试来测试单击 UITableView 中的第一个单元格时图像是不是存在?

显示最后一个单元格时添加表格单元格。在ios中