我正在使用新的Firebase,我正在一个接一个地调用数据库来检索某个对象。在回调中,我将对象添加到CollectionView
数据源,然后调用collectionView.insertItemsAtIndexPaths
。
但是我收到了无效的更新错误。我猜这是因为从数据库中检索的项目如此之快,以至于在下一次更新开始之前,最后一次更新尚未完成。我该如何解决这个问题?
另外,我应该dispatch_async
回调内部的主线程,对吗?
答案 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
更新UICollectionView
,collectionView(_: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)
}