开发者

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 10se开发者_如何学Goconds, 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.


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!


Start the timer in non repeat mode

float interval   = 0.2; //global variable

[NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerSelector:) userInfo:nil repeats:NO];

..........
..........

-(void) timerSelector:(NSTimer *)timer{
  static float timeConsumed = 0.0;
  //do your task which you want to do here
  ............
  ............

 // in the end
   if(timeConsumed > 10.0){
     interval    = 0.5;   //increase the interval so it decrease the speed..
   }else if(timeConsumed > 20.0){
     interval    = 1.0;
   }... go on like this until you stop it..

   timeConsumed   += interval;
   [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerSelector:) userInfo:nil repeats:NO];
}

Written from memory..So syntax errors possible..Correct yourself..hope this helps..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜