-2

I searched on stackoverflow for a tutorial how to use NSUserDefaults. I found this: How to save data in iOS

The whole thing works good as long as I do not close the app completly.

If I double tab the home button and close the app completly, all data is lost when I reopen it.

The Dataholder will then be initilized with score = 0 and level = 0 like defined in the init method.

Could you please help me?

Community
  • 1
  • 1

1 Answers1

0

You can call synchronize after you have made changes to make it write the changes to disk.

[[NSUserDefaults standardUserDefaults] synchronize];

Apple says:

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
w0mbat
  • 2,430
  • 1
  • 15
  • 16
  • Synchronize is not deprecated and is the only call you are given to force values to be written to disk. Do you have a better idea? – w0mbat Dec 04 '14 at 22:41
  • 1
    Yes; let the system write the values to disk asynchronously like it's designed rather than forcing a disk write every time you change a value. See Apple's Foundation release notes about NSUserDefaults for 10.10, as they also apply to iOS. It's been against Apple's best practices to invoke synchronize manually for quite a while. – Jon Shier Dec 04 '14 at 22:53
  • The guy is explicitly saying his changes are not being written. This is the only way to force a write, and you have no better idea. – w0mbat Dec 04 '14 at 23:02
  • Given that he has provided no code or other details, blindly recommending `synchronize` is a bad idea, especially when it goes against Apple's recommend best practice. Unless his usage falls into the very narrow scenarios Apple recognizes might necessitate using `synchronize`, it's not the right solution. – Jon Shier Dec 04 '14 at 23:13
  • Hatters gonna construct elaborate hats. – w0mbat Dec 04 '14 at 23:23