NSUserDefaults Lose Newly Saved Data if App Killed Within 10 Seconds

后端 未结 1 788
鱼传尺愫
鱼传尺愫 2020-12-20 21:06

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,

相关标签:
1条回答
  • 2020-12-20 21:38

    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.

    0 讨论(0)
提交回复
热议问题