views:

84

answers:

2

I have a tabbar-based app with three tabs, one of them is a running clock. To animate the clock UI, I use an NSTimer that fires once a second. If the user will be switching in and out of the various tabs, how should I manage this timer?

  1. Can I just use scheduledTimerWithTimeInterval to create and schedule the timer when the app is first run and let it die when the app closes? Or should I maintain an instance variable for the timer in the rootview controller for the clock tab and use addTimer:forMode: and invalidate?
  2. If the ladder, how often should I add and invalidate the timer? In my viewWillAppear and viewWillDisappear methods for the rootview controller of the clock tab? Somewhere else?

Thanks so much in advance for your wisdom!

+1  A: 

Hi there I would do the following:

if your Clock-View appears -> set the Clock to the current time, then start a timer that updates the clock every second:

clockRefreshTimer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self selector:@selector(updateClockView) userInfo:nil repeats:YES]

if the clock view is about to disappear invalidate the timer

[clockRefreshTimer invalidate];

This way you don't do unnecessary updates.

hope I could help,
sam

samsam
+2  A: 

What @samsam said, plus this: a timer set to 1 second is NOT guaranteed to fire precisely on the second. It'll be scheduled for the next available processing time once a second has passed. In many cases it'll be pretty darn close to the exact time it's scheduled to go, but rarely will it be exactly then, and it might be off by quite a bit if the app is busy with other things.

If it's really critical that your clock actually tick once a second (and it wouldn't be much of a clock if it didn't), you want your timer to fire more often than that, and update the UI when it notices that the time value it's watching has changed.

Dan Ray
yep, you of course are completely right on that one. thx
samsam