【发布时间】: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参数的dequeueReusableCellAPI(这实际上不是崩溃的原因)。