72
62

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift4でDispatchQueueを使う

Last updated at Posted at 2016-10-15

Swift2 -> 3の移行メモ的な記事でしたが、Swift4でもまだ使えるようなので、ちょっと加筆しました(18.09.30)。iosのUIを更新する処理は単一のスレッド(main thread)から実行しなければならない、というルールに従って処理を記述する例です。

DispatchQueue.global().async {
    // 重たい処理
    DispatchQueue.main.async {
    	// UIを更新する処理
    }
}

例えば、1秒おきにラベルのテキストを更新する処理だと以下のようになります。

var i = 1
DispatchQueue.global().async {
    while true {
        Thread.sleep(forTimeInterval: 1)
        DispatchQueue.main.async {
            self.label.text = "\(i)"
            i += 1
        }
    }
}

ちなみに、同じ処理をTimerで実装すると以下のようになります。上記例の場合、こちらの方が(わざわざsleepを入れるより)適していそうです。

var i = 1
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in
    self.label.text = "\(i)"
    i += 1
}

--

72
62
0

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
72
62

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?