1

这是我在使用 iOS 9 和 10 的设备上遇到的错误:

*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“当集合视图中只有 1 个部分时,请求第 9223372036854775807 部分之前的项目数”

这个错误对我来说似乎很清楚,但是我无法理解为什么在装有 iOS 11 的设备上没有发生这种情况。

我不知道如何解决它。

这是我的代码:

extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let cell = self.outletWeatherForecastCollectionView.cellForItem(at: self.currentIndexPath) as? MainTileCollectionViewCell { 
        // Some stuff...
    }
}

崩溃发生在这里。这是当用户切换日期等时触发的协议方法......

显然我的 currentIndexPath 有问题。

这是我的初始化:

 var currentIndexPath : IndexPath = []

在 viewDidLoad 中:

self.currentIndexPath = IndexPath(item: 0, section: 0)

如何保护我的代码以使其不会崩溃?你能解释一下从 iOS 9/10 到 iOS 11 的 collectionView 之间的变化行为吗(预取除外)。

4

2 回答 2

3

发生的事情是设置currentIndexPath = []没有为其分配任何值itemor section; 它正在创建一个“空” IndexPath (IndexPath 对象基本上是任意长度的元组或值数组,可以这样创建/操作)。任何试图以这种方式使用它的代码(例如将其传递给cellForItem调用)都可能具有未定义的行为。看起来有些东西有效地将缺失section值解释为 -1,然后其他东西将 -1 解释为无符号 64 位整数

相反,如果您想使用与现在相同的一般逻辑,我建议声明indexPath为可选:

var currentIndexPath: IndexPath?

然后,在 currentIndexPath 的用法中使用 if-let 语法:

extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let currentIndexPath = currentIndexPath,
        let cell = outletWeatherForecastCollectionView.cellForItem(at: currentIndexPath) as? MainTileCollectionViewCell { 
        // Some stuff...
    }
}

这遵循 Swift 习惯用法,并明确了以“未知”索引路径开始的概念。

但是 - 正如@picciano 的回答所暗示的那样,您可能需要重新考虑您的整体设计,以更好地适应 iOS 应用程序的更大设计模式。

于 2017-12-07T15:49:08.833 回答
0

我建议稍微改变一下你的方法。让您的集合视图单元子类负责更新自身,可能来自通知。尝试保留索引路径或对单元格的引用总是有问题的,因为它们倾向于被重用。

于 2017-12-07T15:54:31.603 回答