如何处理多个NSTimer?

时间:2011-08-17 04:34:17

标签: iphone nstimer

我有一个函数让我们说onTimer

-(void)onTimer {
       * Some Operation *
}

我想以这种方式调用此方法......

10秒钟它应该每0.2秒调用一次....然后在另外10秒内,调用此方法的持续时间应该增加.....这样做会显示从快速模式运行缓慢...它会在最后停止。

请指导。

2 个答案:

答案 0 :(得分:1)

我认为用2个定时器很容易实现。在.h文件中,声明2个定时器:

float intervalYouWant;
NSTimer * timer1;
NSTimer * timer2;

在.m文件中,

- (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];
}

这应该每10秒取消第一个计时器,并以新的时间间隔重新启动它。不要忘记在dealloc方法中使计时器无效。希望有所帮助!

答案 1 :(得分:0)

以非重复模式启动计时器

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];
}

从记忆中写出。所以语法错误可能......自己纠正..希望这有帮助..