xcode 检查计时器是否正在运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44423574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:01:10  来源:igfitidea点击:

Check if Timer is running

iosswiftxcodeswift3nstimer

提问by Hyman Sullivan

I have been trying to refill in game lives with a timer, but whenever I leave a view and return, the timer duplicates and becomes faster. I have tried to address this with the Timer?.isValidfunction to only run the timer when it is invalid so it never duplicates, but it cannot seem to check is the timer is invalidin an if statement.

我一直在尝试用计时器重新填充游戏生活,但是每当我离开视图并返回时,计时器就会重复并变得更快。我试图用Timer?.isValid函数来解决这个问题,只在定时器无效时运行它,所以它永远不会重复,但它似乎无法检查if 语句中的定时器是否无效

This is the if statement that I have been using so far:

这是迄今为止我一直在使用的 if 语句:

if (myTimer?.isValid){
} else{
//start timer
}

Any help would be appreciated, thanks.

任何帮助将不胜感激,谢谢。

回答by Matias Jurfest

You need to check if your Timerinstance isValid(not the Timerclass), let's say: if myTimer.isValid? {}.

您需要检查您的Timer实例isValid(不是Timer类),例如:if myTimer.isValid? {}.

回答by vadian

I recommend to use self-checking startTimer()and stopTimer()functions, the timer will be started only if it's not currently running, the stop function sets the timervariable reliably to nil.

我建议使用自检startTimer()stopTimer()函数,计时器只有在当前未运行时才会启动,停止函数将timer变量可靠地设置为nil.

var timer : Timer?

func startTimer()
{
    if timer == nil {
        timer = Timer.scheduledTimer...
    }
}

func stopTimer()
{
    if timer != nil {
       timer!.invalidate()
       timer = nil
    }
}