如何在Swift中检查NSTimer是否正在运行? [英] How to check if a NSTimer is running or not in Swift?
问题描述
如何在Swift中检查NSTimer是否正在运行。在obj-c中,代码应如下所示:
if(!myTimer){
// DO
}
我正试图在Swift中设置它并且显示错误。
if!myTimer {
// DO
}
我所做的(两种语言)都是让我的计时器变弱。在swift中,它将是一个弱选项。
weak var myTimer:NSTimer?
然后我用
$ b <$ p创建一个计时器$ p>
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.
这篇关于如何在Swift中检查NSTimer是否正在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!