为什么NSUserDefaults没有保存我的值? [英] Why is NSUserDefaults not saving my values?
问题描述
您好我正在尝试使用 NSUserDefaults
在数据库中保存一些默认值。我可以将值保存在 NSUserDefaults
中(甚至在 NSLog
中检查它)。
现在我需要重新启动应用程序时app delegate中的值。但我在 NSUserDefaults
中没有得到任何东西。以下是我班上的代码,我将值保存在 NSUserDefaults
中:
Hi I am trying to use NSUserDefaults
to save some default values in database. I am able to save the values in the NSUserDefaults
(even checked it in NSLog
).
Now I need the values in app delegate when the application is restarted. But I am not getting anything in the NSUserDefaults
. Following is my code from my class where I save the values in NSUserDefaults
:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:appDel.dictProfile forKey:@"dict"];
NSLog(@"%@",[prefs valueForKey:@"dict"]);
以下是来自App Delegagte的代码:
Following is my code from App Delegagte:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(@"%@",[prefs valueForKey:@"dict"]);
上面的代码总是返回null。
有人可以帮助我吗?
the above code always returns me null. Can some one please help me?
推荐答案
如果您通过按主页按钮终止您的应用程序(在模拟器中)或者在设备上),您的 NSUserDefaults
将被保存。
If you terminate your app by pressing the home button (in the Simulator or on the device), your NSUserDefaults
will get saved.
如果您通过按停止终止您的应用程序在Xcode中(在模拟器或设备上),您的 NSUserDefaults
可能得到保存,但他们很可能不会。 NSUserDefaults
会定期保留所有更改,如果您在持久化过程之前终止该过程,它们就会消失。您可以通过调用强制保存:
If you terminate your app by pressing "Stop" in Xcode (in the Simulator or on the device), your NSUserDefaults
might get saved, but there's a good chance they won't. NSUserDefaults
persists any changes periodically, and if you terminate the process before they've been persisted, they'll be gone. You can force the save by calling:
[[NSUserDefaults standardUserDefaults] synchronize];
在iOS4的(这个答案最初写的时候IOS3是公开发行),你的 NSUserDefaults的
按主页按钮时可能无法保存。手动调用 [NSUserDefaults的standardUserDefaults]同步]
在 applicationDidEnterBackground:
应该确保你的 NSUserDefaults的
被正确保存(这应该是IMO的内置行为)。
In iOS4 (this answer was originally written when iOS3 was the public release), your NSUserDefaults
may not get saved when pressing the home button. Manually calling [[NSUserDefaults standardUserDefaults] synchronize]
in applicationDidEnterBackground:
should ensure that your NSUserDefaults
are saved correctly (this should really be a built-in behaviour IMO).
这篇关于为什么NSUserDefaults没有保存我的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!