插入到CollectionView中会引发无效的更新错误

时间:2016-09-02 08:14:20

标签: ios swift firebase firebase-realtime-database collectionview

我正在使用新的Firebase,我正在一个接一个地调用数据库来检索某个对象。在回调中,我将对象添加到CollectionView数据源,然后调用collectionView.insertItemsAtIndexPaths

但是我收到了无效的更新错误。我猜这是因为从数据库中检索的项目如此之快,以至于在下一次更新开始之前,最后一次更新尚未完成。我该如何解决这个问题?

另外,我应该dispatch_async回调内部的主线程,对吗?

3 个答案:

答案 0 :(得分:2)

如果问题是您的查询在上一次完成之前被调用,那么解决方案很简单。

你将把每个查询完成的函数(最后一个除外)放到每个函数中,然后你将逐个调用它们。

假设您有两个查询queryOne和queryTwo。

func queryOne(completion: Result<Void> -> Void)  {

//Below the line that you complete the query 
//Usually after the for loop if you have
completion(.Success())

}

func queryTwo()  {


}

现在你必须在viewDidLoad

中同步它们
queryOne() { result in
            switch result {
            case .Success:
                self.locationManager.delegate = self
                queryTwo()

            case .Failure( _): break // Handle error
            }



        }

答案 1 :(得分:0)

UICollectionView中,numberOfItemsInSection:返回的项目数必须与块中实时更新的项目数相匹配。要解决这种差异,您应该做的是维护一个整数,该整数计算要在集合视图中显示的项目数,并返回该项,而不是yourArray.count。此外,您应该在yourCollectionView.performBatchUpdates({})

中维护此整数

答案 2 :(得分:0)

数据源首先更新其项目计数,然后调用performBatchUpdates更新UICollectionViewcollectionView(_:numberOfItemsInSection:)返回更新后项目计数,它会混淆collectionView.performBatchUpdates。< / p>

解决方案:添加一个属性作为项目计数,并在performBatchUpdates闭包中更新它

func updateItems(updates: [ItemUpdate]) {
    collectionView.performBatchUpdates({
      for update in updates {
          switch update {
         case .Add(let index):
              collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
              itemCount += 1
          case .Delete(let index):
              collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
              itemCount -= 1
          }
      }
  }, completion: nil)
}