Tristan Diependael
Tristan Diependael

Reputation: 623

How to use sleep in swift 2.2

When I use sleep(1), my app sleeps through the whole loop instead of 1 sec. After 90 sec. the labels get updated instead of every sec.

code:

    while time < 90 {
        let goal = Int(arc4random_uniform(MAX) + MIN)

        if goal < 5 {
            scoreA = scoreA + 1
        } else if goal > 15 {
            scoreB = scoreB + 1
        }

        time = time + 1
        scoreLabel.text = "\(scoreA) - \(scoreB)"
        timeLabel.text = "\(time) min."
        sleep(1)
    }

Upvotes: 1

Views: 357

Answers (2)

Seurahepo
Seurahepo

Reputation: 151

I agree on the answer by @arsen, but I'll try to answer why this happens.

You are setting text of UILabel, this would indicate your code is running on the main thread. You call sleep() on every roll of the while loop, which in this case blocks the main thread for 90 seconds. While the main thread is blocked, UI becomes unresponsive.

It is advised that code on the main thread executes and exits as fast as possible so that the UI stays as responsive and fluid as possible.

Upvotes: 2

Arsen
Arsen

Reputation: 10951

I think NSTimer more suitable in this case.

let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)

Upvotes: 2

Related Questions