gpt4 book ai didi

ios - swift:异步任务+完成

转载 作者:搜寻专家 更新时间:2023-10-30 22:32:42 26 4
gpt4 key购买 nike

我对 swift 中的异步任务有很多困惑。我想做的是这样的......

 func buttonPressed(button: UIButton) {
// display an "animation" tell the user that it is calculating (do not want to freeze the screen
// do some calculations (take very long time) at the background
// the calculations result are needed to update the UI
}

我试着做这样的事情:

func buttonPressed(button: UIButton) {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) { () -> Void in
// display the animation of "updating"
// do the math here
dispatch_async(dispatch_get_main_queue(), {
// update the UI
}
}
}

但是,我发现没有等待我的计算完成就更新了 UI。我对异步队列的使用感到很困惑。有人帮忙吗?谢谢。

最佳答案

您需要一个带有异步完成处理程序的函数。

计算结束时调用completion()

func doLongCalculation(completion: () -> ())
{
// do something which takes a long time
completion()
}

buttonPressed 函数中,在后台线程上调度计算函数,并在完成后返回主线程以更新 UI

func buttonPressed(button: UIButton) {
// display the animation of "updating"
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.doLongCalculation {
dispatch_async(dispatch_get_main_queue()) {
// update the UI
print("completed")
}
}
}
}

关于ios - swift:异步任务+完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39250589/

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