Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults Lose Newly Saved Data if App Killed Within 10 Seconds

I'm looking for a faster way to save user preferences than the NSUserDefaults. I've found that if the app is killed within around 10 seconds of writing to NSUserDefaults, it will not be saved permanently. I use the defaults to save paths to custom ring tones, paths to custom images, map coordinates, and basically just user defined preferences. Is using core data the better option? SQLite? What's accepted as the fastest and most lightweight?

like image 866
Tommy Devoy Avatar asked Dec 20 '12 21:12

Tommy Devoy


1 Answers

You need to be sure to call synchronize to save the data immediately.

[[NSUserDefaults standardUserDefaults] synchronize];

From Apple's class reference:

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.

And to answer your second question, it really depends on how much data you want to store. NSUserDefaults is designed to store very small amounts of data (for preferences) like the state of a toggle switch, etc. You can get away with storing the paths to images and ring tones here but it isn't exactly advisable. By that I mean you can, but probably shouldn't.

Core Data is a much better approach if you plan on storing many of these paths as it is very scalable and performs very well. So overall, if you need to store a lot of data, user Core Data, or as another alternative store the paths in a plist in the documents directory.

like image 155
Mick MacCallum Avatar answered Oct 14 '22 19:10

Mick MacCallum