0

I've been using Xcode to implement a timer and run calculations off the time. However every so often the timer will skip an interation, which throws off all the calculations.

- (void)Time
{

  if (running==false) return;

  NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
  NSTimeInterval elapsed = currentTime - startTime;

  int mins = (int) (elapsed / 60.0);

  elapsed -= mins* 60;
  int seconds = (int) (elapsed);
  elapsed -= seconds;
  int fraction = elapsed * 100.0;
  beepTime = [self Dec:seconds+elapsed];



  [self mod];



  label.text= [NSString stringWithFormat:@"%u:%02u.%.01u",mins,seconds,fraction/10];



  [self performSelector:@selector(Time) withObject:nil afterDelay:0.01];


}

Here is a small sample of some logs

2012-08-14 20:25:04.659  RT 8.470000  BP 50.710000 MT 8.360000
2012-08-14 20:25:04.671  RT 8.470000  BP 50.720000 MT 8.370000
2012-08-14 20:25:04.682  RT 8.470000  BP 50.740000 MT 8.390000

note that BP 50.730000 and MT 8.380000 have been skipped.

Any suggestions?

Cheers!

1 Answers1

1

If you read the documentation on -performSelector:withObject:afterDelay: it makes no guarantees that the message is sent exactly after 0.01 seconds delay. Instead it says that the message is put to event queue after 0.01 seconds and fired whenever it is its turn.

You might be better off by using NSTimer's method + scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:.

Eventhough timer works also in the current run loop similarly than performSelector, atleast it wouldn't execute in 0.01 + (time it took to execute -Time method body).

Note that you need to call that NSTimer method only once and use its returned value to invalidate the timer.

samuke
  • 450
  • 1
  • 5
  • 15