How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?

前端 未结 9 1649
甜味超标
甜味超标 2020-12-10 01:06

I\'m developing a game and I want to create a pause menu. Here is my code:

self.view?.paused = true

but NSTimer.scheduledTimerWithT

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 01:50

    Even though the solutions exposed here are good, I thought an important insight was missing. Like a lot of people here explained, timer invalidate() and recreate is the best option. But one could argue that you could do something like this:

    var paused:Bool
    
    func timerAction() {
        if !paused {
            // Do stuff here
        }
    }
    

    is easier to implement, but it will be less efficient.

    For energy impact reasons, Apple promotes avoiding timers whenever possible and to prefer event notifications. If you really need to use a timer, you should implement pauses efficiently by invalidating the current timer. Read recommendations about Timer in the Apple Energy Efficiency Guide here: https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/MinimizeTimerUse.html

提交回复
热议问题