如何立即在iPhone上存储设置?
是否可以立即在iPhone上存储设置?iOS 4+上的应用程序在退出时不会关闭,如果我按Xcode设置中的“停止进程”,是否不会保存?如何拯救他们如何立即在iPhone上存储设置?,iphone,xcode,ipad,ios4,nsuserdefaults,Iphone,Xcode,Ipad,Ios4,Nsuserdefaults,是否可以立即在iPhone上存储设置?iOS 4+上的应用程序在退出时不会关闭,如果我按Xcode设置中的“停止进程”,是否不会保存?如何拯救他们 - (void)compLoad { compTotal = [[NSUserDefaults standardUserDefaults] integerForKey: @"compTotal"]; compCount = [[NSUserDefaults standardUserDefaults] integerForKey: @"
- (void)compLoad {
compTotal = [[NSUserDefaults standardUserDefaults] integerForKey: @"compTotal"];
compCount = [[NSUserDefaults standardUserDefaults] integerForKey: @"compCount"];
compShow = [[NSUserDefaults standardUserDefaults] boolForKey: @"compShow"];
}
- (void)compSave {
[[NSUserDefaults standardUserDefaults] setInteger: compTotal forKey: @"compTotal"];
[[NSUserDefaults standardUserDefaults] setInteger: compCount forKey: @"compCount"];
[[NSUserDefaults standardUserDefaults] setBool: compShow forKey: @"compShow"];
}
只需调用
[[NSUserDefaults standardUserDefaults]同步]代码>。但通常你不需要这样做:一旦你的应用程序进入后台,iOS会保存,在其他一些情况下也会保存。调用同步
太频繁被认为是一件坏事(tm)。根据文档,以下调用将保留任何未完成的修改。要检查此操作是否成功,请检查此调用的返回值。值为“是”表示成功
[[NSUserDefaults standardUserDefaults] synchronize];
尝试使用同步
方法
<强> Update <强>:您应该考虑注册默认值,如在
中建议的那样。
此外,根据本指南(“同步和检测首选项更改”),关于同步:
要检测首选项值何时发生更改,应用程序还可以注册通知NSUserDefaultsIDChangeNotification。每当shared NSUserDefaults对象检测到某个持久性域中的首选项发生更改时,它就会向您的应用程序发送此通知。您可以使用此通知响应可能影响用户界面的更改。例如,您可以使用它检测用户首选语言的更改,并适当更新应用程序内容
如果您想直接重新读取设置,您肯定仍然需要使用同步。[[NSUserDefaults standardUserDefaults]同步]强>
synchronize-此方法在定期调用时自动调用
间隔,仅当无法等待自动间隔时才使用此方法
同步(例如,如果应用程序即将退出)或
如果您想更新用户默认磁盘上的内容,即使
您没有做任何更改
在AppDelegate
- (void)applicationWillResignActive:(UIApplication *)application
{
// Call your compSave here to force saving before app is going to the background
}
也
是数据很重要-这是件好事)谢谢你的回答。既然同步
是正确的解决方案(我肯定知道,过去几年我在几个项目中使用了NSUserDefaults),那么你的问题肯定出在别处了。也许你在什么地方覆盖了你的设置?例如,如果在应用程序启动时在compLoad
之前意外调用compSave
,则会再次得到“空”值。在compSave
和compLoad
上设置一个断点,看看在启动应用程序时首先调用哪个断点。您是否在我上面提到的AppDelegate方法中调用了compSave
?每次变量更改后我都会调用它。您能否提供有关失败原因的更多信息?您用于设置和获取用户默认值的代码可能会有所帮助?
- (void)applicationWillResignActive:(UIApplication *)application
{
// Call your compSave here to force saving before app is going to the background
}
- (void)compSave
{
[[NSUserDefaults standardUserDefaults] setInteger: compTotal forKey: @"compTotal"];
[[NSUserDefaults standardUserDefaults] setInteger: compCount forKey: @"compCount"];
[[NSUserDefaults standardUserDefaults] setBool: compShow forKey: @"compShow"];
[[NSUserDefaults standardUserDefaults] synchronize];
}