是否可以将计时器的状态保存在用户默认值中?

发布于 2024-08-08 09:10:07 字数 176 浏览 2 评论 0原文

我有一个标签,上面显示倒计时器。

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

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

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初懵 2024-08-15 09:10:07

是的,只需将应用程序关闭的时间和剩余倒计时时间存储在 NSUserDefaults 中即可。当应用程序再次启动时,您可以从 NSUserDefaults 中获取关闭时间和剩余时间。使用当前时间,可以通过简单的数学计算倒计时剩余的修正时间。

像这样的东西可能会起作用,当然未经测试:

// 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"];

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"];
三生一梦 2024-08-15 09:10:07

或者您可以只计算您希望其过期的日期/时间(NSDate)并将其保存在默认值中。重新启动时,与该日期进行比较,了解它是否已过期,或者您是否需要设置一个计时器来捕获未来的过期时间。

Or you could just calculate the date/time (NSDate) you want it to expire and save that in your defaults. On relaunch compare against that date to know if it has expired or if you need to set a timer to catch the future expiration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文