如何判断 iPhone 应用程序是否由后台启动

发布于 2024-09-09 19:24:38 字数 329 浏览 9 评论 0原文

我的应用程序使用 NSUserDefaults 来存储一些值,以便它可以在应用程序更新或后台退出时恢复它们。后台自动保存我的整数值,但如果用户从启动器退出应用程序,数字也会丢失,并且我猜进入后台时不会调用 ViewDidUnload 方法。有没有一种方法可以让我在应用程序卸载时随时保存 NSUserDefaults。此外,ViewDidLoad 方法也有同样的问题,它不会从后台调用。有什么办法解决这个问题吗?

PS 到目前为止,我的应用程序需要保存的唯一数据是用于屏幕计数的 int。

更新: UIApplicationDidEnterBackgroundingNotification 非常适合您的建议!

My application uses NSUserDefaults to store some values so that it can restore them on application update or if backgrounding is quit. Backgrounding automatically saves my integer values, but if the user quits the application from the launcher, the numbers are lost too, and the ViewDidUnload method I guess doesn't evoke when entering backgrounding. Is there a way that I can save the NSUserDefaults any time the application unloads. Also, the ViewDidLoad method had the same problem, it doesn't evoke from backgrounding. What's a way around this?

P.S. So far the only data my application needs to save is an int for an on-screen count.

UPDATE: UIApplicationDidEnterBackgroundingNotification works great with your suggestions!

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

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

发布评论

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

评论(2

甜心 2024-09-16 19:24:38

您无法在数据最终被杀死之前保存数据,但您可以在 applicationDidEnterBackground: 应用程序委托。

还有 applicationDidBecomeActive:,但没有理由从那里加载保存的数据,因为当从后台的应用程序调用它时,数据将被以任何方式保留。

You can't save data right before it eventually gets killed, but you can save state 'just in case' in your applicationDidEnterBackground: app delegate.

There's also applicationDidBecomeActive:, but there's no reason to load your save data from there, since when it's invoked from an app that was in the background, the data will have been preserved any way.

七分※倦醒 2024-09-16 19:24:38

您无法判断您的应用程序是否是从后台启动的,至少无法判断它当前的设置方式,因为如果您的应用程序委托是从跳板启动的,它将获得相同的事件序列。

正如 Joost 所说,您应该在 applicationDidEnterBackground 回调中保存恢复状态所需的任何内容;本质上,您应该假设这是您的应用程序在被邪恶进程收割者无情杀死之前收到的最后一条消息。

您应该查看 WWDC 2010 会议视频,特别是会议 105 - 采用多任务处理有关 iPhone OS 第 1 部分的详细说明。

You can't tell if your app was launched from the background or not, at least how it's currently set up, since your app delegate will get the same sequence of events if it's launched from springboard.

As Joost says, you should save anything you need to restore state inside the applicationDidEnterBackground callback; essentially, you should assume this is the last message your app will get before it gets killed mercilessly by an evil process reaper.

You should check out the WWDC 2010 Session Videos, specifically, Session 105 - Adopting Multitasking on iPhone OS, Part 1 for a thorough explanation.

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