且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-29 11:23:34

我所做的(两种语言)都是让我的计时器变弱。在swift中,它将是一个弱选项。

  weak var myTimer:NSTimer? 

然后我用



$ b myTimer = NSTimer.scheduledTimerWithTimeInterval(1,
target:self,
selector:timerFired:,
userInfo:nil,
重复: false)

然后你可以使用

 如果计时器== nil 

告诉它是否正在运行。



要停止计时器,只需拨打

  myTimer?.invalidate ()

在Objective-C中它将是

  [myTimer invalidate]; 

这在Objective-C中有效,因为向nil指针发送消息是有效的,并且什么都不做。 / p>

如果您不想使用弱选项,您可以查看计时器,看看它是否正在运行,通过查看有效 property。


How to check if NSTimer is running or not in Swift. In obj-c the code should be like this as I guess:

if (!myTimer) {
  //DO
}

I'm trying to set it in Swift like this and it's showing errors.

if !myTimer {
 // DO
}

What I do (in both languages) is to make my timer weak. In swift it would be a weak optional.

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

[myTimer invalidate];

That works in Objective-C because sending messages to nil pointers is valid, and just does nothing.

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.