是否可以在“用户默认设置"中保存计时器的状态?

编程入门 行业动态 更新时间:2024-10-27 20:32:12
本文介绍了是否可以在“用户默认设置"中保存计时器的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个标签,上面显示了倒数计时器.

I have a label on which I am showing countdown timer.

现在,如果我关闭我的应用,计时器将关闭,标签文本也将关闭.我知道我们可以保存标签的文本值.但是,当应用再次启动时,我们如何显示正确的倒计时.

Now if I close my app the timer will be off and the label's text also. I know that we can save the label's text value. But how do we show the correct countdown when the app starts again.

假设我再次启动应用3分钟后,我在00:05:35关闭,标签应该显示00:02:35,并且计时器应该在那里剩余倒计时

Suppose I close at 00:05:35 after 3 minutes when app is launched again the label should show 00:02:35 and the timer should be there for remaining countdown

推荐答案

是的,只需在NSUserDefaults中存储关闭应用程序的时间和倒计时所需的时间.当应用再次启动时,您会从NSUserDefaults获得关闭时间以及剩余时间.使用当前时间,这是简单的数学运算,可以计算倒计时剩余的校正时间.

Yes, simply store the time at which your app was closed and the time left to count down in NSUserDefaults. When the app starts again you get the time it was closed from NSUserDefaults and the time left. Using the current time it's simple math calculating the corrected time left on your count down.

像这样的事情可能会成功完成,当然未经测试:

Something like this might do the trick, untested of course:

// save state NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSDate *now = [NSDate date]; double countDown = 45.0; // in seconds, get this from your counter [userDefaults setObject:now forKey:@"timeAtQuit"]; [userDefaults setDouble:countDown forKey:@"countDown"]; [userDefaults synchronize]; // restore state NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSDate *timeAtQuit = [userDefaults objectForKey:@"timeAtQuit"]; double timeSinceQuit = [timeAtQuit timeIntervalSinceNow]; double countDown = timeSinceQuit + [userDefaults doubleForKey:@"countDown"];

更多推荐

是否可以在“用户默认设置"中保存计时器的状态?

本文发布于:2023-11-28 14:49:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642854.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   默认设置   状态   用户   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!