【问题标题】:App Crashes When (insertItems) is Called The Second Time on CollectionView Swift在 CollectionView Swift 上第二次调用 (insertItems) 时应用程序崩溃
【发布时间】:2018-08-23 18:47:28
【问题描述】:

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

代码:

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

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database uicollectionview


    【解决方案1】:

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

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

    还请注意,在使用集合视图时,您应该创建一个带有itemsectionIndexPath。将rowsection 与表格视图一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多