How do I check if an NSTimer is running?
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开发者_如何学C (/*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!
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?
I would recommend using a nil check to determine if your timer is running or not.
...
//Define _tapTimer in .h
if (_tapTimer) {//do something
}
else{
_tapTimer = [[NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:NO] retain];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: _tapTimer forMode: NSDefaultRunLoopMode];
}
...
-(void)timerFired:(NSTimer*)timer
{
if(timer == _tapTimer)
{
//Handle timerfired
[_tapTimer release], _tapTimer = nil;
}
}
You can query the RunLoop to know if there is such a timer inside the loop
CFRunLoopRef loopRef = [[runner currentRunLoop] getCFRunLoop];
Boolean timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)timer ,kCFRunLoopDefaultMode)
if (timerAdded)
{
...
}
but, I haven't tested that code yet
精彩评论