UICollectionView NSInternalInconsistencyException

时间:2017-01-02 17:19:23

标签: ios swift collectionview

我正在使用无限滚动更新UICollectionView。加载其他项目后,新项目将添加到collectionView,如下所示。

                self?.loadMoreItems({ (complete, content) in

                if (complete && content.count > 0) {
                    DispatchQueue.main.async {
                        var indexPaths = [IndexPath]()
                        let index = self?.myFeed!.count

                        print("COUNT IS ")
                        print(content.count)

                        for item in content {
                            let indexPath = IndexPath(item: index! + 1, section: 0)
                            indexPaths.append(indexPath)
                            self!.myFeed!.append(item)
                        }

                        collectionView.performBatchUpdates({ () -> Void in
                            collectionView.insertItems(at: indexPaths)
                        }, completion: { (finished) -> Void in
                            DispatchQueue.main.async {
                                collectionView.scrollToItem(at: indexPaths[indexPaths.count - 1], at: .bottom, animated: true)
                                collectionView.finishInfiniteScroll()
                            }
                        });

                    }}
                else {
                    DispatchQueue.main.async {
                        collectionView.finishInfiniteScroll()
                    }
                }
            })

几乎所有时间都可以正常工作,但有时候,通常只下载一个附加项目时,我会遇到以下异常:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert item 11 into section 0, but there are only 11 items in section 0 after the update'

更新

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if myFeed != nil {
        return myFeed!.count
    }
    else  {
        return 0
    }
}

0 个答案:

没有答案