gpt4 book ai didi

ios - 调度组错误

转载 作者:行者123 更新时间:2023-11-28 05:59:50 25 4
gpt4 key购买 nike

因此,我正在尝试重组我的 API 调用以利用 dispatchGroups,这样我就不必如此快速地重新加载 collectionViews 和其他元素。我知道对于调度组,您通常必须创建一个,进入,然后离开一定次数。完成此操作后,您通常会通知主队列执行一些操作。但是,在下面的代码片段中,它甚至在我进入调度组之前就通知了主队列。这是把事情扔掉了。如果有人可以查看我的代码并告诉我出了什么问题,我将不胜感激。

 static func showFeaturedEvent(for currentLocation: CLLocation,completion: @escaping ([Event]) -> Void) {
//getting firebase root directory
let dispatchGroup1 = DispatchGroup()
var currentEvents:[Event]?
var geoFireRef: DatabaseReference?
var geoFire:GeoFire?
geoFireRef = Database.database().reference().child("featuredeventsbylocation")
geoFire = GeoFire(firebaseRef: geoFireRef!)
let circleQuery = geoFire?.query(at: currentLocation, withRadius: 17.0)
circleQuery?.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in
print("Key '\(key)' entered the search area and is at location '\(location)'")
dispatchGroup1.enter()
print("entered dispatch group")
EventService.show(forEventKey: key, completion: { (event) in
if let newEvent = event {
currentEvents?.append(newEvent)
dispatchGroup1.leave()
print("left dispatch group")
}
})

})
dispatchGroup1.notify(queue: .main, execute: {
if let currentEventsFinal = currentEvents{
completion(currentEventsFinal)
}
})
}

我在其他地方运行调度组。我不确定这是否会影响任何事情,但我觉得在这个问题中注意这一点很重要。

最佳答案

您需要在开始异步任务之前进入组,并在异步任务完成时离开。在第一个异步任务完成之前,您不会执行第一个 enter,因此当执行命中您的 notify 时,调度组为空并立即触发。

调用 leave 的次数与调用 enter 的次数相同也很重要,否则该组将永远不会为空,因此请谨慎调用 leave 在条件语句中。

static func showFeaturedEvent(for currentLocation: CLLocation,completion: @escaping ([Event]) -> Void) {
//getting firebase root directory
let dispatchGroup1 = DispatchGroup()
var currentEvents:[Event]?
var geoFireRef: DatabaseReference?
var geoFire:GeoFire?
geoFireRef = Database.database().reference().child("featuredeventsbylocation")
geoFire = GeoFire(firebaseRef: geoFireRef!)
let circleQuery = geoFire?.query(at: currentLocation, withRadius: 17.0)

disatchGroup1.enter()

circleQuery?.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in
print("Key '\(key)' entered the search area and is at location '\(location)'")

dispatchGroup1.enter()

EventService.show(forEventKey: key, completion: { (event) in
if let newEvent = event {
currentEvents?.append(newEvent)
print("left dispatch group")
}

dispatchGroup1.leave()

})

dispatchGroup1.leave()

})

dispatchGroup1.notify(queue: .main, execute: {
if let currentEventsFinal = currentEvents{
completion(currentEventsFinal)
}
})
}

关于ios - 调度组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50142518/

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