Skip to content

Instantly share code, notes, and snippets.

@oliverbarreto
Created January 4, 2014 17:24
Show Gist options
  • Select an option

  • Save oliverbarreto/8257681 to your computer and use it in GitHub Desktop.

Select an option

Save oliverbarreto/8257681 to your computer and use it in GitHub Desktop.
Create a Timer or Clock with "not 100% precision" based on NSTimers
// Create an Outlet for a UIlabel on storyboard and set its text property to it...
- (void)startTimer
{
if (_timer == nil) {
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(timerTick:)
userInfo:nil
repeats:YES];
}
}
- (void)stopTimer
{
[_timer invalidate];
_timer = nil;
}
- (void)timerTick:(NSTimer *)timer
{
// Timers are not guaranteed to tick at the nominal rate specified, so this isn't technically accurate.
// However, this is just an example to demonstrate how to stop some ongoing activity, so we can live with that inaccuracy.
_ticks += 0.1;
double seconds = fmod(_ticks, 60.0);
double minutes = fmod(trunc(_ticks / 60.0), 60.0);
double hours = trunc(_ticks / 3600.0);
self.timerLabel.text = [NSString stringWithFormat:@"%02.0f:%02.0f:%04.1f", hours, minutes, seconds];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment