【问题标题】:Call DispatchGroup() in the right place在正确的地方调用 DispatchGroup()
【发布时间】:2018-01-15 13:16:22
【问题描述】:

我想使用DisaptchGroup 在迭代后调用func 并将元素附加到数组中。

这是firebase节点的样子

 {
       "tags": {
           "NewYork": {
                 uid1: 1
                 uid2: 1
           }, 
          "baseball": {
                 uid1: 1
           }
        }
    }

所以,基本上我所做的是在用户选择标签之后,获取标签下的 uid 并将这些 uid 传递给数组。

func filterTempo(filterTag: FilteredTags) {

        let group = DispatchGroup()
        let tag = filterTag.selectedTag.components(separatedBy: "/") //it reutrns "NewYork" and "baseball"

            tag.forEach { (key) in
                self.ref.child("tags").child(key).observe(.value, with: { (snapshot) in
                    guard let dictionary = snapshot.value as? [String:Any] else { return }
                    for (key,_) in dictionary {
                        self.arrays.append(key)
                    }
           // want call func after iteration has finished.
                }, withCancel: nil)
            }
    }//func

第一次迭代后,数组将像这样[uid1, uid2]。然后在第二次迭代之后,数组将看起来像这样[uid1, uid2, uid1]。我想在迭代完成而不是中途之后调用函数(func fetchTeams(array: [String]))。为了实现这一点,我尝试使用DispatchGroup,但我在func fetchTeams 中尝试了print(array),它会像这样返回。

[uid1, uid2]
[uid1, uid2, uid1]

我应该在哪里打电话给DispatchGroup.enter()DispatchGroup.leave() 来解决这个问题? 提前谢谢!

【问题讨论】:

    标签: arrays swift firebase-realtime-database dispatch dispatch-async


    【解决方案1】:

    您必须在每次之前致电group.enter() 致电observe。在每个observe 闭包中,工作完成后,您调用group.leave()。 一旦 enterleave 调用的数量取消(例如,所有输入的块都已离开),queue.notifiy 闭包将被调用,然后您将调用 fetchTerms 或其他东西:

    func filterTempo(filterTag: FilteredTags) {
    
        let group = DispatchGroup()
        let tag = filterTag.selectedTag.components(separatedBy: "/") //it reutrns "NewYork" and "baseball"
    
            tag.forEach { (key) in
                group.enter()
                self.ref.child("tags").child(key).observe(.value, with: { (snapshot) in
                    guard let dictionary = snapshot.value as? [String:Any] else { return }
                    for (key,_) in dictionary {
                        self.arrays.append(key)
                    }
                    group.finished()
                }, withCancel: {
                    // Maybe do some error handling here.
                    group.finished()
                })
            }
            group.notify(queue: DispatchQueue.main)  {
                // called after all blocks have been finished.
                self.fetchTeams(self.arrays)
            }
    }//func
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-31
      • 2015-03-04
      • 2021-11-07
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多