【问题标题】:Index out of range for indexPath swiftindexPath swift的索引超出范围
【发布时间】:2016-07-08 12:51:07
【问题描述】:

我正在制作一个需要用户点击多个单元格才能选择它们的应用程序。当他们点击一个单元格时,会出现一个 .Checkmark 附件项目。出于某种原因,尽管每当我尝试访问该 VC 时,应用程序都会崩溃,并且我在第 8 行收到以下错误消息(如果!checked[indexPath.row]):

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell: InstrumentTableCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? InstrumentTableCell


        cell.configurateTheCell(recipies[indexPath.row])

        if !checked[indexPath.row] {
            cell.accessoryType = .None
        } else if checked[indexPath.row] {
            cell.accessoryType = .Checkmark
        }
        return cell
    }

这是我的工作检查方法:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark {
                cell.accessoryType = .None
                checked[indexPath.row] = false
            } else {
                cell.accessoryType = .Checkmark
                checked[indexPath.row] = true
            }
        }
    }

【问题讨论】:

  • 好的,你的checked 方法是什么样的?
  • pbodsk 我更新了问题以添加选中的方法:)
  • 啊...好的,所以checked 是一个数组,您可以在其中存储是否检查了一行,对吗?
  • 是的,检查商店是否检查了一行
  • 它看起来像 checked.count == 0checked == nil 在你做 if !checked[indexPath.row] 的那一刻

标签: swift uitableview swift2 nsindexpath exc-bad-instruction


【解决方案1】:

您的问题是当tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 被调用时,您只在checked 数组中存储 项。但是,只有在您实际选择了一行时才会调用该方法。

另一方面,每次需要渲染新表格单元格时都会调用tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)

所以当你在cellForRowAtIndexPath 提问时:

if !checked[indexPath.row]

那么你就不能确定checked 实际上包含任何东西。例如,当您第一次开始渲染单元格时,您的 checked 数组不包含任何值,因此当您在没有值的位置向它询问值时它会崩溃。

一种解决方案是初始化您的checked 数组以包含所有false 值。我猜你有一些名为recipies 的模型数组,所以你可以这样做:

for (index, _) in recipies.enumerate() {
    checked.append(false)
}

或者正如@AaronBrager 在下面的 cmets 中所建议的那样(这更漂亮:))

checked = Array(count:recipies.count, repeatedValue:false)

这样您就可以确定您的已检查数组已正确初始化,并使用与您的接收方相同数量的元素。

另一种选择是让recipies 中的各个元素知道它们是否被选中。

希望这是有道理的,对你有帮助。

【讨论】:

  • 您也可以使用checked = Array(count:recipes.count, repeatedValue:false) 来启动数组并填充错误值
  • 我知道有人有更好的主意 :) 如果你不介意@AaronBrager,我会更新答案
猜你喜欢
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2016-11-10
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多