我有一個異步 api 呼叫,我正在使用委托模式并分配了一個協議方法來處理當我們收到來自 api 的回應時如何處理資料
didWeatherUpdate
我在委托中實作了這一點。我理解它的方式,在異步網路請求完成之前,我用來使用來自 api 的資料更新 UI 的這種方法不會觸發。
我的問題是為什么需要明確告訴主執行緒它是一個異步行程。如果在api呼叫完成后資料準備好之前不會呼叫該函式。我的假設是,當資料準備好時,函式會觸發,然后添加到主執行緒作業的佇列中。從完整的堆疊背景來看,這似乎是額外的
func didWeatherUpdate(_ weatherManager: WeatherManager,_ weather: WeatherModel){
print("\(weather.temperature) from the controller")
DispatchQueue.main.async{
self.temperatureLabel.text = weather.temperatureString
}
uj5u.com熱心網友回復:
這是你的功能
func didWeatherUpdate(_ weatherManager: WeatherManager,_ weather: WeatherModel){
print("\(weather.temperature) from the controller")
DispatchQueue.main.async{
self.temperatureLabel.text = weather.temperatureString
}
}
此函式在后臺執行緒上呼叫。該print行在該執行緒上完成。
如果您嘗試self.temperatureLabel.text = weather.temperatureString作為下一行而不將其包裝在DispatchQueue異步塊中,那么它將立即在后臺運行并會導致運行時警告,因為您不允許在后臺更新 UI。
要更新 UI,您需要將您的行包裝在一個塊中并將其發送到主佇列而不是等待它。這正是它的作用
DispatchQueue.main.async {
self.temperatureLabel.text = weather.temperatureString
}
這里async沒有告訴主佇列資料獲取是異步的。意思是您希望將塊異步發送到主佇列,而不是讓后臺執行緒等待 UI 更新。如果你在這之后有print一行,它可能發生在 UI 更新之前。
如果您希望后臺執行緒等待 UI,您可以使用DispatchQueue.main.sync.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477702.html
