objective-c 如何查找 NSTimer 是否处于活动状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1635803/
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-03 22:25:33  来源:igfitidea点击:

How to find if NSTimer is active or not?

objective-cxcodeiphone-sdk-3.0nstimerinvalidation

提问by Rahul Vyas

I have a something like this:

我有这样的事情:

 NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(updateCountdown)
                                                 userInfo:nil
                                                  repeats:YES]; 

I am updating a label's text using this timer. Not at a certain condition I want to check if timer is active then invalidate the timer. My question is how do I find that timer is active or not?

我正在使用此计时器更新标签的文本。不是在特定条件下我想检查计时器是否处于活动状态然后使计时器无效。我的问题是如何确定计时器是否处于活动状态?

回答by Kevin

When a non repeating timer fires it marks itself as invalid so you can check whether it is still valid before cancelling it (and of course then ridding yourself of it).

当一个非重复计时器触发时,它会将自己标记为无效,因此您可以在取消它之前检查它是否仍然有效(当然然后摆脱它)。

if ( [timer isValid] && yourOtherCondition){
    [timer invalidate], timer=nil;
}

In your case you have a repeating timer so it will always be valid until you take some action to invalidate it. Looks like in this case you are running a countdown so it will be up to you to make sure you invalidate and rid yourself of it when the countdown reaches the desired value (In your updateCountdown method)

在您的情况下,您有一个重复计时器,因此在您采取某些措施使其无效之前,它始终有效。看起来在这种情况下,您正在运行倒计时,因此当倒计时达到所需值时,您可以确保无效并摆脱它(在您的 updateCountdown 方法中)

回答by NSResponder

NSTimerhas an -isValidmethod.

NSTimer-isValid方法。

回答by ianh

Keep the timer in an instance variable, and set timer = nilwhen there's no timer running (i.e. after you call [timer invalidate]). Then, to check if the timer is active, you can just check whether timer == nil.

将计时器保存在一个实例变量中,并timer = nil在没有计时器运行时(即在您调用 之后[timer invalidate])进行设置。然后,要检查计时器是否处于活动状态,您只需检查timer == nil.

回答by Crashalot

In Swift, you can use the isValidboolean to see if the timer is running:

在 Swift 中,您可以使用isValid布尔值来查看计时器是否正在运行:

if timer.isValid {
   // Do stuff
}

From the Apple docs:

来自苹果文档

A Boolean value that indicates whether the receiver is currently valid. (read-only)

true if the receiver is still capable of firing or false if the timer has been invalidated and is no longer capable of firing.

一个布尔值,指示接收器当前是否有效。(只读)

如果接收器仍然能够触发,则为 true;如果计时器已失效且不再能够触发,则为 false。