简体   繁体   English

在应用程序终止之间保留NSUserDefaults信息

[英]Persisting NSUserDefaults information between application terminations

In iOS4, when I save NSUserDefaults, the information gets saved. 在iOS4中,当我保存NSUserDefaults时,信息将被保存。 But then, if the application becomes inactive, and I kill the application (by double clicking the home button and then terminating the app), and launch the application again, the NSUserDefaults are not read. 但是,如果应用程序变为非活动状态,并且我终止应用程序(通过双击主页按钮然后终止应用程序),并再次启动应用程序,则不会读取NSUserDefaults。

Now, is this the default behaviour of NSUserDefaults that if the app is terminated due to any of the issues, the next launch will not store the information? 现在,这是NSUserDefaults的默认行为,如果应用因任何问题而终止,下次启动将不会存储信息吗?

The call I am using to persist the info is:- 我用来保持信息的电话是: -

[[NSUserDefaults standardUserDefaults] registerDefaults:
     [NSDictionary dictionaryWithObjectsAndKeys:
      "Some date", @"Validity",
      nil]];

after you register defaults add this 注册默认值后添加此项

[[NSUserDefaults standardUserDefaults] synchronize];

until you synchoronize, the standardUserDefaults gives current/correct values as long as the app is alive. 在您同步之前,只要应用程序处于活动状态,standardUserDefaults就会提供当前/正确的值。

once the app is terminated, since you didn't sync the standardUserDefaults, the app will read the unsynced values on the next launch. 一旦应用程序终止,由于您没有同步standardUserDefaults,应用程序将在下次启动时读取未同步的值。

Example: Think of it like a google doc that you are editing. 示例:将其视为您正在编辑的Google文档。

the AutoSave feature of google document is equivalent to the nsuserdefaults synchornize. google文档的AutoSave功能相当于nsuserdefaults synchornize。 If you close the browser before the changes you made to the document has been autosaved, the next time you load it up, you'll see the old content. 如果您在对文档所做的更改已自动保存之前关闭浏览器,则下次加载时,您将看到旧内容。

The call you mention to persist the user defaults, registerDefaults , does not actually persist anything to disk. 您提到的用于保持用户默认值registerDefaults的调用实际上并不会将任何内容保留到磁盘上。 What registerDefaults does is initialize the defaults to use for the application if it can't find any on the disk. registerDefaults作用是初始化用于应用程序的默认值,如果它在磁盘上找不到的话。 You should do this on each application launch, typically in the initialize method for the app delegate. 您应该在每次应用程序启动时执行此操作,通常在app delegate的initialize方法中执行此操作。

Once your application is running it will typically modify the user defaults. 应用程序运行后,通常会修改用户默认值。 Whenever you want to save these modified defaults to the disk you should call: 每当您想要将这些修改过的默认值保存到磁盘时,您应该调用:

[[NSUserDefaults standardUserDefaults] synchronize];

After the defaults have been saved they will be loaded automatically on any subsequent application launches. 保存默认值后,将在任何后续应用程序启动时自动加载它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM