应用程序崩溃何时(insertItems)在CollectionView Swift上第二次调用

时间:2018-03-15 03:54:11

标签: 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] {
            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)
                }
            }

enter image description here enter image description here

1 个答案:

答案 0 :(得分:2)

您尝试在循环中添加多个新值,但一次添加一个。将它们全部分批插入一个插件会好得多。

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...中的此代码在主队列上运行。

另请注意,使用集合视图时,应创建IndexPath itemsection。使用rowsection与表格视图。