简体   繁体   English

如何在Swift中检查NSTimer是否正在运行?

[英]How to check if a NSTimer is running or not in Swift?

How to check if NSTimer is running or not in Swift. 如何在Swift中检查NSTimer是否正在运行。 In obj-c the code should be like this as I guess: 在obj-c中代码应该像我猜的那样:

if (!myTimer) {
  //DO
}

I'm trying to set it in Swift like this and it's showing errors. 我试图像这样在Swift中设置它并显示错误。

if !myTimer {
 // DO
}

What I do (in both languages) is to make my timer weak. 我所做的(两种语言)都是让我的计时器变弱。 In swift it would be a weak optional. 在swift中,它将是一个弱选项。

weak var myTimer: NSTimer?

Then I create a timer with 然后我创建一个计时器

myTimer = NSTimer.scheduledTimerWithTimeInterval(1,
          target: self,
          selector: "timerFired:",
          userInfo: nil,
          repeats: false)

And then you can use 然后你可以使用

if timer == nil

to tell if it's running. 告诉它是否正在运行。

To stop the timer you just call 要停止计时器,只需拨打电话即可

myTimer?.invalidate()

In Objective-C it would be 在Objective-C中它会是

[myTimer invalidate];

That works in Objective-C because sending messages to nil pointers is valid, and just does nothing. 这在Objective-C中有效,因为向nil指针发送消息是有效的,并且什么都不做。

If you don't want to use a weak optional, you can query a timer to see if it's running by looking at it's valid property. 如果您不想使用弱可选项,则可以通过查看计时器的valid属性来查询计时器以查看它是否正在运行。

How about the below option? 以下选项怎么样? Can you see if this works for you 你能看出这对你有用吗?

if myTimer.valid {
}
if !myTimer.valid {
    //DO
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM