swift:异步任务+完成
swift: async task + completion
我对 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 没有等待我的计算完成就更新了。我对异步队列的使用感到很困惑。有人帮忙吗?谢谢
dispatch_queue_t dispatchqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchqueue, ^(void){
while ([self calculate]) {
NSLog(@"calculation finished");
dispatch_async(dispatch_get_main_queue(), ^{
// update the UI
});
}
});
- (BOOL)calculate
{
//do calculation
//return true or false based on calculation success or failure
return true;
}
您需要一个带有异步完成处理程序的函数。
计算调用结束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")
}
}
}
}
我对 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 没有等待我的计算完成就更新了。我对异步队列的使用感到很困惑。有人帮忙吗?谢谢
dispatch_queue_t dispatchqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchqueue, ^(void){
while ([self calculate]) {
NSLog(@"calculation finished");
dispatch_async(dispatch_get_main_queue(), ^{
// update the UI
});
}
});
- (BOOL)calculate
{
//do calculation
//return true or false based on calculation success or failure
return true;
}
您需要一个带有异步完成处理程序的函数。
计算调用结束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")
}
}
}
}