當用戶點擊一個按鈕時,會觸發一個由 API 呼叫和計算組成的冗長函式。
@IBAction func buttonTapped(_ sender: Any) {
var itemIndex = 0
let dispatchGroup = DispatchGroup()
for name in (entireRecipe?.extendedIngredients!)! {
dispatchGroup.enter()
CalculatorService().calculate() { item in
self.arrayItem.append(item)
self.totalItems = self.arrayItems.reduce(0, )
}
itemIndex = itemIndex 1
}
dispatchGroup.leave()
dispatchGroup.notify(queue: .main) {
print("DispatchGroup Notified")
self.itemLabel.text = "\(self.totalItems)"
}
}
我上面的理由是:
- 當for-in回圈開始時進入dispatchGroup
- 在 for-in 回圈遍歷整個陣列后,dispatchGroup 被留下
- dispatchGroup 才被通知,并且 UI 標簽被更新
但是,它看起來dispatchGroup.notify沒有按預期運行,因此在 for-in 回圈完成后 UI 標簽沒有更新。
dispatchGroup我的代碼有什么遺漏嗎?任何幫助深表感謝!
uj5u.com熱心網友回復:
該leave線必須在閉包內
for name in (entireRecipe?.extendedIngredients!)! {
dispatchGroup.enter()
CalculatorService().calculate() { item in
self.arrayItem.append(item)
self.totalItems = self.arrayItems.reduce(0, )
dispatchGroup.leave()
}
itemIndex = itemIndex 1
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462287.html
上一篇:在沒有UI執行緒的專用后端服務器上使用異步代碼有優勢嗎?
下一篇:更新變數異步等待
