UICollectionView中的断言失败?

4

我有一些在线托管的图像,它们被解析成我的UICollectionViewCell中的UIImageView。当我进入和退出视图时,经常会崩溃并在调试器中出现以下错误:

*** Assertion failure in -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:], /SourceCache/UIKit/UIKit-3347.44.2/UICollectionView.m:3870
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete item 0 from section 0 which only contains 0 items before the update'
*** First throw call stack:
(0x1839702d8 0x19563c0e4 0x183970198 0x184824ed4 0x188a74348 0x100150300 0x100117c4c 0x100117d88 0x18332f010 0x1848571c4 0x1847a8604 0x1847981cc 0x184859f28 0x101410f94 0x101415c28 0x1839277f8 0x1839258a0 0x1838512d4 0x18d2a76fc 0x18844ef40 0x10011a1d4 0x195ce6a08)

这个错误的原因是什么,我该如何解决? 更新 我注意到当我segue到collectionView并在任何cell加载之前迅速返回时,程序会崩溃。但是这不应该是导致崩溃的原因。我应该如何解决这个问题?
这是我的cellForIndex方法:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
        // Configure the cell
        let book = self.books[indexPath.row]
        let coverImage = book.coverImage
        if coverImage == nil {
            book.fetchCoverImage({ (image, error) -> Void in
                collectionView.reloadItemsAtIndexPaths([indexPath])
            })
        } else {
            let imageView = cell.imageView
            imageView.image = book.coverImage
        }
        return cell
    }

添加一个异常断点并查看调用堆栈以确定问题所在 - 展示你的代码。 - Paulw11
我尝试过了,但这次它没有崩溃。而我问题中提到的错误实际上是一个NSException异常,当我在集合视图屏幕加载任何内容之前突然退出时会发生这种情况。这就是我观察到的情况@Paulw11 - Mike Strong
请展示更多代码。cellAtIndex,... - tuledev
我认为问题出在这个代码块 { (image, error) -> Void in collectionView.reloadItemsAtIndexPaths([indexPath]) } 在你退出集合视图时被调用。你可以尝试检查 collectionView != nil,或者使用一个标志来判断是否退出并中断这个代码块吗? - tuledev
你可以在回答中提供那段代码吗? - Mike Strong
显示剩余2条评论
1个回答

0
尝试打破reloadItems的块。
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
        // Configure the cell
        let book = self.books[indexPath.row]
        let coverImage = book.coverImage
        if coverImage == nil {
            book.fetchCoverImage({ (image, error) -> Void in
                if collectionView != nil { // <--- something like this. I'm not sure. Just take the idea: try to check before reload.
                    collectionView.reloadItemsAtIndexPaths([indexPath])
                }
            })
        } else {
            let imageView = cell.imageView
            imageView.image = book.coverImage
        }
        return cell
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接