简体   繁体   English

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

[英]App Crashes When (insertItems) is Called The Second Time on CollectionView Swift

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

在此处输入图片说明 在此处输入图片说明

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. 我不使用Firebase,但据我了解,它的完成处理程序在主队列上调用。 If not, this code needs to be updated so this code inside if let snapDict... is run on the main queue. 如果没有,则需要更新此代码,以便在主队列中运行if let snapDict...内部的代码。

Also note that you should create an IndexPath with an item and a section when working with a collection view. 另请注意,在使用集合视图时,应使用itemsection创建IndexPath Use row and section with a table view. 在表格视图中使用rowsection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM