2016-08-31 11 views
3

私は、非同期タスクを非常に多く混乱させました。swift:async task + completion

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が完了するために私の計算を待たずに更新されていることがわかる:

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 
} 

が、私はこのような何かをしようとした...このような何か私は何をしたいです。私は非同期キューの使用についてかなり混乱しています。誰でも助けますか?ありがとう。

+0

ておりUIを更新するバックグラウンドスレッドで、バックメインスレッドの完了後に計算関数の終わりに

'//ここで数学を行い、サーバーにリクエストしますか? – bbarnhart

+0

いいえ、ちょうど私が画面を凍結したくないかなり長い時間がかかります計算を行う... :( – user6539552

答えて

5

非同期補完ハンドラを持つ関数が必要です。計算コールbuttonPressed機能ディスパッチにおいてcompletion()

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

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") 
     } 
    } 
    } 
} 
0
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; 
} 
+1

待っていることはかなり悪い方法です。 – vadian

+0

それは動作しません:( – user6539552