gpt4 book ai didi

arrays - 在正确的地方调用 DispatchGroup()

转载 作者:行者123 更新时间:2023-11-28 15:07:16 25 4
gpt4 key购买 nike

我想使用 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]。我想在迭代完成后调用 function( func fetchTeams(array: [String]) ) 而不是中途。为实现这一点,我尝试使用 DispatchGroup 但我在 func fetchTeams 中尝试了 print(array) 并且它像这样返回。

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

我应该在哪里调用 DispatchGroup.enter()DispatchGroup.leave() 来解决这个问题?提前致谢!

最佳答案

每次调用 observe 之前,您都必须调用 group.enter()。在每个 observe 闭包中,工作完成后,调用 group.leave()。一旦 enterleave 调用的次数抵消(例如,所有输入的 block 都已离开),将调用 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

关于arrays - 在正确的地方调用 DispatchGroup(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48263776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com