我应该如何在标签栏 iPhone 应用程序中管理我的 NSTimer?
我有一个基于选项卡栏的应用程序,带有三个选项卡,其中一个是运行时钟。为了对时钟 UI 进行动画处理,我使用每秒触发一次的 NSTimer。如果用户将在各个选项卡之间切换,我应该如何管理这个计时器?
- 我可以在应用首次运行时使用
scheduledTimerWithTimeInterval
创建和安排计时器,并在应用关闭时让它终止吗?或者我应该在时钟选项卡的 rootview 控制器中维护计时器的实例变量并使用 addTimer:forMode: 和 invalidate 吗? - 如果是梯子,我应该多久添加和无效计时器?在时钟选项卡的 rootview 控制器的
viewWillAppear
和viewWillDisappear
方法中?其他地方?
预先非常感谢您的智慧!
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?
- 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 useaddTimer:forMode:
andinvalidate
? - If the ladder, how often should I add and invalidate the timer? In my
viewWillAppear
andviewWillDisappear
methods for the rootview controller of the clock tab? Somewhere else?
Thanks so much in advance for your wisdom!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@samsam 所说的,加上这一点:设置为 1 秒的计时器不能保证在第二秒精确触发。一旦一秒过去,它将被安排到下一个可用的处理时间。在许多情况下,它会非常接近预定的确切时间,但很少会恰好在那个时间,而且如果应用程序忙于其他事情,它可能会偏离相当多的时间。
如果你的时钟实际上每秒滴答一次真的很重要(如果不是的话,它就不会是一个时钟),你希望你的计时器触发得比这更频繁,并在注意到它正在观看的时间值已经改变。
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.
我会执行以下操作:
如果您的时钟视图出现 ->将时钟设置为当前时间,然后启动一个每秒更新时钟的计时器:
如果时钟视图即将消失,则使计时器无效
这样您就不会进行不必要的更新。
希望我能帮忙,
山姆
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:
if the clock view is about to disappear invalidate the timer
This way you don't do unnecessary updates.
hope I could help,
sam