LoginSignup
39
37

More than 5 years have passed since last update.

[Swift] 非同期処理の関数を同期的に実行したい

Last updated at Posted at 2015-07-29

が、やり方がわからない。
自力でやってみるとこんな感じでできることはできたのだが・・・。

swift
//非同期処理が完了したらtrueになる変数を用意
var isDone:Bool = false
//BoltsをインストールしてcontinueWithSuccessBlockを使用
HidoukiFunc().continueWithSuccessBlock {(task) in
    //HidoukiFuncの実行が完了した際
    isDone = true
    return nil
}
//isDoneがtrueになるのを待つ
while isDone == false {
    usleep(10)
}

こんなの絶対おかしい。
もっと賢い方法があるはず。
わかったら追記します。

追記:
わかりました。

swift
//セマフォを用意する
let semaphore:dispatch_semaphore_t = dispatch_semaphore_create(0)

//BoltsをインストールしてcontinueWithSuccessBlockを使用
HidoukiFunc().continueWithSuccessBlock {(task) in
    //HidoukiFuncの実行が完了した際
    //セマフォを+1する(-1から0へ)
    dispatch_semaphore_signal(semaphore)
    return nil
}
//セマフォを-1する(セマフォが0になるまで処理が進まないのでここでウェイトということになる)
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

参考:
GCDリファレンス
一週間分の歩数を取得する

変更(2015/08/10):
説明に自信がない箇所を削除

39
37
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
37