Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pause and resume NSTimer in iphone

hello I am developing small gameApp. I need to pause the timer,when user goes to another view [say settings view]. when user comes back to that view , I need to resume the timer.

can anybody solve this issue ...

Thanks in Advance...

like image 566
Hardik Patel Avatar asked Nov 10 '10 12:11

Hardik Patel


1 Answers

NSTimer does not give you the ability to pause it. However, with a few simple variables, you can create the effect yourself:

NSTimer *timer;
double timerInterval = 10.0;
double timerElapsed = 0.0;
NSDate *timerStarted;

-(void) startTimer {
  timer = [NSTimer scheduledTimerWithTimeInterval:(timerInterval - timerElapsed) target:self selector:@selector(fired) userInfo:nil repeats:NO];
  timerStarted = [NSDate date];
}

-(void) fired {
  [timer invalidate];
  timer = nil;
  timerElapsed = 0.0;
  [self startTimer];
  // react to timer event here
}

-(void) pauseTimer {
  [timer invalidate];
  timer = nil;
  timerElapsed = [[NSDate date] timeIntervalSinceDate:timerStarted];
}

This has been working out quite well for me.

like image 65
tybro0103 Avatar answered Oct 06 '22 09:10

tybro0103