【问题标题】:How do I fix ,Unexpectedly found nil while unwrapping an Optional value, in my code如何修复,在我的代码中展开可选值时意外发现 nil
【发布时间】:2019-03-26 21:26:30
【问题描述】:

我的代码有问题,一切正常,然后我开始收到此错误

"线程 1:致命错误:在展开一个文件时意外发现 nil 可选值”

当我让我的单元格变量成为可重用单元格时发生错误。

这是我的代码,错误发生在声明 let cell 的第 3 行。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let song = songs[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell") as! SongCell
    cell.setSong(song: song)
    return cell
}

更新:我已经修复了致命错误,但我现在得到了

“线程1:信号SIGABRT”

当我添加此代码以设置表视图数据源和委托时发生错误。

override func viewDidLoad() {
            super.viewDidLoad()
            songs = createArray()
            playlists = createArray2()
            tableView.dataSource = self
            tableView.delegate = self
            tableView2.dataSource = self    //Adding this causes app to crash
            tableView2.delegate = self  //Adding this causes the app to crash

        // Do any additional setup after loading the view, typically from a nib.
    }  

每当我删除此代码时,应用程序就会启动,但表格视图中不会显示任何单元格。

【问题讨论】:

  • 这可能是一个问题,将单元格转换为您的 SongCell 类型(as!)。故事板中的单元格绝对是正确的类吗?
  • 很可能自定义单元格的类未在 Interface Builder 中设置为 SongCell。正如答案中所建议的那样,使用带有indexPath 参数的dequeueReusableCell API(这实际上不是崩溃的原因)。

标签: ios swift xcode


【解决方案1】:

您缺少dequeueReusableCell 的第二个参数

let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath) as! SongCell

确保注册一个 nib 或类

tableView.register(UINib(nibName: "NibSongCell", bundle: nil), forCellReuseIdentifier: "SongCell")

// if using a custom cell, replace UITableViewCell.self with that class
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SongCell")

【讨论】:

  • 现在我的应用委托文件中出现“线程 1:信号 SIGABRT”错误。它发生在“class AppDelegate: UIResponder, UIApplicationDelegate {”这一行。我检查了所有标签和输出是否有错误,但没有。
  • 如果单元格在 Interface Builder 中设计为原型单元格,您不得注册该单元格。
猜你喜欢
  • 2020-10-22
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 2016-10-18
相关资源
最近更新 更多