Reputation: 27
Basically the first time this runs it's perfect then the second time it crashes. I have some pictures that show which line of code it crashes on. The issue seems to do with perform batch.
Code:
let ref = Database.database().reference().child("test")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject] {
for snap in snapDict {
if snap.key == "testValue" {
self.log.performBatchUpdates({
let indexPath = IndexPath(row: group.count, section: 0)
group.append("textHere")
self.log.insertItems(at: [indexPath])
}, completion: nil)
}
}
Upvotes: 0
Views: 410
Reputation: 318955
You are trying to add multiple new values in a loop but one at a time. It's much better to batch them all into a single insert.
let ref = Database.database().reference().child("test")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject] {
var newPaths = [IndexPath]()
for snap in snapDict {
if snap.key == "testValue" {
let indexPath = IndexPath(item: group.count, section: 0)
newPaths.append(indexPath)
group.append("textHere")
}
}
if !newPaths.isEmpty {
self.log.insertItems(at: newPaths)
}
}
}
I don't use Firebase but it is my understanding that its completion handlers are called on the main queue. If not, this code needs to be updated so this code inside if let snapDict...
is run on the main queue.
Also note that you should create an IndexPath
with an item
and a section
when working with a collection view. Use row
and section
with a table view.
Upvotes: 2