Ios 在CollectionView Swift上第二次调用(插入项)时,应用程序崩溃

Ios 在CollectionView Swift上第二次调用(插入项)时,应用程序崩溃,ios,swift,firebase,firebase-realtime-database,uicollectionview,Ios,Swift,Firebase,Firebase Realtime Database,Uicollectionview,基本上,它第一次运行时是完美的,然后第二次崩溃。我有一些图片显示它在哪一行代码上崩溃。问题似乎与执行批处理有关 代码: let ref = Database.database().reference().child("test") ref.observeSingleEvent(of: .value, with: { (snapshot) in if let snapDict = snapshot.value as? [String:AnyObject] {

基本上,它第一次运行时是完美的,然后第二次崩溃。我有一些图片显示它在哪一行代码上崩溃。问题似乎与执行批处理有关

代码:

  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)
                }
            }

您试图在循环中添加多个新值,但一次添加一个。最好将它们全部批处理到单个插入中

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)
        }
    }
}
我不使用Firebase,但据我所知,它的完成处理程序是在主队列上调用的。如果没有,则需要更新此代码,以便在主队列上运行
If let snapDict…
中的此代码


还请注意,在使用集合视图时,应使用
项和
节创建
索引XPath
。在表视图中使用

您试图在循环中添加多个新值,但一次只能添加一个。最好将它们全部批处理到单个插入中

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)
        }
    }
}
我不使用Firebase,但据我所知,它的完成处理程序是在主队列上调用的。如果没有,则需要更新此代码,以便在主队列上运行
If let snapDict…
中的此代码

还请注意,在使用集合视图时,应使用
项和
节创建
索引XPath
。在表格视图中使用