1

我的代码:

    DataService.dataService.fetchDataFromServer { (channel) in
        self.channels.append(channel)
        let indexPath = IndexPath(item: self.channels.count - 1, section: 0)
        self.collectionView?.insertItems(at: [indexPath])
    }

从服务器函数获取数据:

 func fetchDataFromServer(callBack: @escaping (Channel) -> ()) {
        DataService.dataService.CHANNEL_REF.observe(.childAdded, with: { (snapshot) in
            let channel = Channel(key: snapshot.key, snapshot: snapshot.value as! Dictionary<String, AnyObject>)
            callBack(channel)
        })
    }

项目数量部分:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return 0
}

完整错误:

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

我正在使用集合视图,但不知道为什么会出现此错误。

任何帮助,将不胜感激!

4

4 回答 4

4

numberOfItemsInSection返回 0,所以当告诉集合视图你正在添加一个项目时,当这个方法说集合中仍然有 0 个项目时,它会感到不安。

您的代码甚至有注释// #warning Incomplete implementation, return the number of items

你可能想要这样的东西:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return self.channels.count
}
于 2016-11-24T04:09:15.273 回答
2

我遇到了同样的问题,并修复了将 [unowned self] 放入闭包并强制 UI 更新在主线程上完成的问题。此外,正如其他人所说,numberOfItemsInSection 方法应该返回数组中的项目数。这是我的最终代码:

DataManager.fetchDish() { [unowned self] dish in
        if let dish = dish {
            DispatchQueue.main.async {
                self.dishes.append(dish)
                self.dishesCollectionView.insertItems(at: [IndexPath(row: self.dishes.count - 1, section: 0)])
            }
        }
    }
于 2018-08-19T17:42:51.433 回答
1

确保你连接了数据源,这让我很吃惊,因为它是如此基础,有时你不会考虑它。

于 2018-11-23T15:57:26.503 回答
0

dataSource对于遇到此问题的其他用户,在尝试更新未分配的 TableView 或 CollectionView 时也会出现这些错误。确保 TableViewdataSource已连接(使用情节提要或 nib 时)或以编程方式分配。

于 2021-09-13T09:11:18.037 回答