简体   繁体   中英

Persisting NSUserDefaults information between application terminations

In iOS4, when I save NSUserDefaults, the information gets saved. 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.

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?

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.

once the app is terminated, since you didn't sync the standardUserDefaults, the app will read the unsynced values on the next launch.

Example: Think of it like a google doc that you are editing.

the AutoSave feature of google document is equivalent to the 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. What registerDefaults does is initialize the defaults to use for the application if it can't find any on the disk. You should do this on each application launch, typically in the initialize method for the app delegate.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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