奇怪的NSUserDefaults行为 [英] Strange NSUserDefaults behavior

查看:61
本文介绍了奇怪的NSUserDefaults行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iPhone应用程序正在运行时,我在NSUserDefaults中存储了一些数据(NSStrings).我存储的只是游戏的高分.当我双击主页"按钮并终止应用程序时,重新启动应用程序时,我存储在NSUserDefaults中的值通常不存在.为什么会这样?

While my iPhone app is running I store some data (NSStrings) in the NSUserDefaults. I'm storing the high score for a game just fyi. When I double-tap the home button and kill the app the values I store in NSUserDefaults are often not there when I restart the app. Why is this happening?

我使用的代码在所有预多任务操作系统(3.0等)中均能正常工作.通过阅读/搜索网络,看来 [NSUserDefaults standardUserDefaults]同步]; 可能会有所帮助.有什么想法吗?

The code I'm using was working fine in all the pre-multitasking OSs (3.0 etc). From reading/searching the net it looks like doing [NSUserDefaults standardUserDefaults] synchronize]; could help. Any thoughts?

谢谢!

推荐答案

在任务栏被挂起时将其杀死是向其发送SIGKILL消息;没有正常关机.

Killing an app from the taskbar when it's suspended just sends it the SIGKILL message; no graceful shutdown happens.

如果您正在后台运行并终止该应用程序,则在该应用程序终止之前,您可能无法使用户默认设置同步(写入磁盘),这通常在内部计时器上自行发生,但是如果您已写入默认值,然后事物在自动同步发生之前被挂起,这可以解释这种现象.

If you're backgrounding and then killing the app, you might not be getting the user defaults synchronized (written to disk) before the app dies, which happens by itself on an internal timer usually, but if you've written to the defaults and then the thing gets suspended before the auto-synchronize happens, that could explain this behavior.

将此(如您所述)放入:

Put this (as you note):

 [[NSUserDefaults standardUserDefaults] synchronize];

在应用程序委托的 -applicationDidEnterBackground 处理程序中

.这样,即使该应用在后台运行时死掉或被杀死,您也知道已经编写了默认设置.

in your -applicationDidEnterBackground handler in the app delegate. That way, even if the app dies or is killed while it's in the background, you know the defaults have been written.

作为一种防御措施,通常我每次写出我认为非常重要的状态时都对默认对象进行显式调用.

As a defensive practice, I generally explicitly call synchronize on the defaults object every time I write state that I consider critically important.

这篇关于奇怪的NSUserDefaults行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆