如何检查 NSTimer 是否正在运行?
我有一个 IBAction,按下按钮后,它会创建一个计划外的计时器。然后,如果同一个计时器已经启动,//做一些事情,否则启动创建的计时器。 这是我到目前为止所得到的:
- (IBAction)button1Press {
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];
NSTimer *tapTimer = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:NO];
if (/*tapTimer is running*/) {//do something
}else{
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: tapTimer forMode: NSDefaultRunLoopMode];
}
}
我的问题是把什么作为条件。如果我输入 tapTimer isValid 或 != nil 那么它总是返回 true,因为 tapTimer 已经被声明了。我不想使计时器无效或为零,因为按钮的主要目的是仅在 1 秒的时间间隔内按下按钮两次时才执行操作。
如果有一种完全不同的方法来做我想做的事情,那么请告诉我!
谢谢负载!
I have an IBAction where upon the button being pressed, it creates an unscheduled timer. Then, if that same timer has already started, //do something, else start the timer which was created.
Here is what I have so far:
- (IBAction)button1Press {
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];
NSTimer *tapTimer = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:NO];
if (/*tapTimer is running*/) {//do something
}else{
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: tapTimer forMode: NSDefaultRunLoopMode];
}
}
My problem is what to put as the condition. If I put tapTimer isValid or != nil then it always returns true, because tapTimer is already declared. I do not want to invalidate or nil out the timer because the main purpose of the button is to only do the action if the button is pressed twice in a time interval of 1 second.
If there is a completely different approach to do what I want then please do tell!
Thanks loads!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,到目前为止,我看到您正在尝试检查 tapTimer 是否正在运行。我有一个建议。使用变量来指示 TapTimer 是否正在运行。当您运行计时器时,将此变量更改为 true,当计时器的时间达到 0 并调用您选择的方法时,您在此方法中将此变量更改为 false。
这有帮助吗?
From what I understand so far, I see that you are attempting to check whether tapTimer is running or not. I have one suggestion. Use a variable for indicating whether you are having tapTimer running or not. When you run the timer, you change this variable to true, and when the timer's time hits 0 and invoke the method you have selected, you change this variable to false in this method.
Does this help?
我建议使用 nil 检查来确定计时器是否正在运行。
I would recommend using a nil check to determine if your timer is running or not.
您可以查询 RunLoop 以了解循环内是否有这样的计时器
,但是我还没有测试该代码
You can query the RunLoop to know if there is such a timer inside the loop
but, I haven't tested that code yet