简体   繁体   English

我应该如何在tabbar iPhone应用程序中管理我的NSTimer?

[英]How should I manage my NSTimer in a tabbar iPhone app?

I have a tabbar-based app with three tabs, one of them is a running clock. 我有一个基于tabbar的应用程序,有三个选项卡,其中一个是运行时钟。 To animate the clock UI, I use an NSTimer that fires once a second. 要为时钟UI设置动画,我使用每秒触发一次的NSTimer。 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? 我可以在应用程序首次运行时使用scheduledTimerWithTimeInterval来创建和计划计时器,并在应用程序关闭时让它死掉吗? Or should I maintain an instance variable for the timer in the rootview controller for the clock tab and use addTimer:forMode: and invalidate ? 或者我应该在时钟选项卡的rootview控制器中为计时器维护一个实例变量,并使用addTimer:forMode: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? 在我的viewWillAppearviewWillDisappear方法的时钟选项卡的根视图控制器? Somewhere else? 别的地方?

Thanks so much in advance for your wisdom! 非常感谢您的智慧!

What @samsam said, plus this: a timer set to 1 second is NOT guaranteed to fire precisely on the second. 什么@samsam说,加上这个:设置为1秒的计时器不保证在第二秒精确射击。 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. 如果真的很重要的是你的时钟实际上每秒钟打一次(如果不是那么它就不会是一个时钟),你希望你的计时器比这更频繁,并在它注意到时更新UI它看的时间价值已经改变了。

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: 如果出现Clock-View - >将Clock设置为当前时间,则启动一个每秒更新一次的定时器:

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 SAM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM