iOS - fatal error : unexpectedly found nil while unwrapping an Optional value when reloadData() is called

标签 ios swift

我知道有很多关于此错误的问题,但我浏览了所有这些问题,但没有一个有帮助。我从主类中调用函数 addCell() ,下面的代码是我的 TableViewControllerClass 中的代码。我肯定在我的 .storyboard 中链接了 requestIdentifier“cell”,并且数组“locations”和“times”绝对不为空,因为我在错误发生时打印它们,所以问题必须出在我的“table”变量上,它也正确链接到 TableView ,但由于某种原因显然为零。有什么建议吗?

func addCell(){

    //update to insertion sort

    currLocation = addLocation

    if (locations == [""] && times == [0]) {

        self.locations.removeAll()

        self.times.removeAll()

    }

    if !(locations.isEmpty){

        if locations[locations.count-1] != currLocation {

            var count = 0

            var neverVisited = true

            for location in locations{

                if location == currLocation{

                    neverVisited = false

                    times[count] += addTime

                    count++

                }

            }

            if neverVisited {

                locations.append(currLocation)

                times.append(addTime)

            }

        } else {

            times[times.count-1] = addTime

        }

    } else {

        locations.append(currLocation)

        times.append(addTime)

    }

    print(locations) //not empty
    print(times) //not empty

    table.reloadData() //crashes here

}




override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    cell.textLabel?.text = locations[indexPath.row] + ", \(times[indexPath.row])"

    }

    return cell

}

最佳答案

您可以在调用 reloadData 函数之前在 addCell() 函数的末尾或开头(取决于您是否想要执行所有逻辑,即使表尚不存在)使用保护语句来解决问题:

guard let tmpTable = table else {
        return
    }

您还可以使用:

if let tmpTable = table else {
        tmpTable.reloadData()
    }

这样,仅当您的表已加载时才会调用导致问题的函数。 另外,使用主类有点奇怪,通常这个类不用于执行任何代码/逻辑,请尝试使用正确的 Controller 。

关于iOS - fatal error : unexpectedly found nil while unwrapping an Optional value when reloadData() is called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38731814/

相关文章:

ios - 使用应用程序测试数据库的下载速度和最大下载速度

swift - 以编程方式将按钮添加到 GameScene.swift 并在按下时转换场景

c - iOS - 在 plCrashReporter 中使用 PRIx64 打印内存地址

ios - 通过我的 ios 应用程序与 UIActivityViewController 共享文件

ios - 如何使我的自定义手势识别器类实例同时工作?

swift - 为什么我不能创建一个名为 '!' 的后缀运算符

ios - 在 iOS(Swift) 中管理 XML 数据

ios - CoreMotion 在 iOS 10 上延迟传送数据

ios - 如何修复segue后新 View 的显示?

javascript - React 的 webkit.messageHandlers 将 JavaScript 注入(inject) Swift