Search code examples
iosnstimer

Stop an already scheduled nstimer


I am starting a timer to trigger an event based on a false condition.However if the condition becomes true within the scheduled time, i need to stop the event from triggering.

if(!condition)
{
  myTimer =[NSTimer scheduledTimerWithTimeInterval:200 target:self selector:@selector(trigger:) userInfo:nil repeats:NO];
}
else
{
 if([myTimer isvalid])
   [myTimer invalidate]
   myTimer= nil;
}

If condition becomes true within 200 sec don't trigger the @selector.

Invalidating the timer doesn't stop the method from triggering. I can do this by having a BOOL flag, but can i do it using NSTimer's methods.


Solution

  • You must be creating multiple instance of myTimer. Check whether myTimer already initailized or not ?

    if(!condition)
    {
      if(myTimer == nil)
         myTimer =[NSTimer scheduledTimerWithTimeInterval:200 target:self selector:@selector(trigger:) userInfo:nil repeats:NO];
    }
    else
    {
     if([myTimer isvalid])
       { 
         [myTimer invalidate]
          myTimer = nil;
        }
    }