当我使用 "if let" 语句解包可选的 collectionViewCell 时,为什么我的应用程序会崩溃?
Why does my app crash when I use an "if let" statement to unwrap an optional collectionViewCell?
我在 xcode 中收到这个错误,经过几个月的代码运行良好,但我终究无法弄清楚代码抛出错误的原因。
错误:线程 1:致命错误:在展开可选值时意外发现 nil
if let recentsRow = collectionView(collectionView, cellForItemAt: recentsIndex) as? DashboardRowCollectionViewCell {
recentsRow.documents = recents ?? []
}
if let favoritesRow = collectionView(collectionView, cellForItemAt: favoritesIndex) as? DashboardRowCollectionViewCell {
favoritesRow.documents = favorites ?? []
}
很抱歉,如果有人问过这个问题,但我在网站上看了一会儿,仍然无法提出解决方案。
编辑:运行 模拟器中的应用程序时,我没有遇到这个问题。我更新之前也没有这个问题 XCode.
编辑 2:调试器告诉我 collectionView 为 nil,但我仍然不确定为什么它为 nil。
以下是我的 ViewController 中定义 collectionView 的方式:@IBOutlet weak var collectionView: UICollectionView!
虽然我不确定为什么 collectionview 一开始是 nil,但我通过在有问题的代码周围添加以下内容来修复我的应用程序崩溃:
if collectionView != nil {
... code goes here ...
}
这将是公认的答案,直到有人来解释为什么它一开始是零。
编辑:如果您想弄清楚为什么它为零并想要问题所属的 ViewController 代码,我很乐意提供。
我在 xcode 中收到这个错误,经过几个月的代码运行良好,但我终究无法弄清楚代码抛出错误的原因。
错误:线程 1:致命错误:在展开可选值时意外发现 nil
if let recentsRow = collectionView(collectionView, cellForItemAt: recentsIndex) as? DashboardRowCollectionViewCell {
recentsRow.documents = recents ?? []
}
if let favoritesRow = collectionView(collectionView, cellForItemAt: favoritesIndex) as? DashboardRowCollectionViewCell {
favoritesRow.documents = favorites ?? []
}
很抱歉,如果有人问过这个问题,但我在网站上看了一会儿,仍然无法提出解决方案。
编辑:运行 模拟器中的应用程序时,我没有遇到这个问题。我更新之前也没有这个问题 XCode.
编辑 2:调试器告诉我 collectionView 为 nil,但我仍然不确定为什么它为 nil。
以下是我的 ViewController 中定义 collectionView 的方式:@IBOutlet weak var collectionView: UICollectionView!
虽然我不确定为什么 collectionview 一开始是 nil,但我通过在有问题的代码周围添加以下内容来修复我的应用程序崩溃:
if collectionView != nil {
... code goes here ...
}
这将是公认的答案,直到有人来解释为什么它一开始是零。
编辑:如果您想弄清楚为什么它为零并想要问题所属的 ViewController 代码,我很乐意提供。