Search code examples
iphonenstimer

How to Handle multiple NSTimer?


I have a function lets say onTimer

-(void)onTimer {
       * Some Operation *
}

I want to call this method like in this way...

For 10 seconds it should call on every 0.2 seconds.... then in another 10seconds, duration of calling this method should be increased..... by doing this it will appear operations getting slow from fast mode... and it will stop at the end.

Please guide.


Solution

  • I think this is fairly easy to accomplish with 2 timers. In the .h file, declare 2 timers:

    float intervalYouWant;
    NSTimer * timer1;
    NSTimer * timer2;
    

    In the .m file,

    - (void)viewDidLoad; {
      intervalYouWant = 0.2;
      timer1 = [NSTimer scheduledTimerWithTimeInterval:intervalYouWant target:self selector:@selector(methodForTimer1) userInfo:nil repeats:YES];
      timer2 = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(changeTimer1) userInfo:nil repeats:YES];
    }
    
    - (void)changeTimer1; {
      [timer1 invalidate];
      timer1 = nil;
      intervalYouWant += amountYouWantToAdd;
      timer1 = [NSTimer scheduledTimerWithTimeInterval:intervalYouWant target:self selector:@selector(methodForTimer1) userInfo:nil repeats:YES];
    }
    

    That should cancel the first timer every 10 seconds, and restart it with a new time interval. Don't forget to invalidate the timers in the dealloc method. Hope that helps!