1

I am using UserDefaults to store a small array on the back press of a navigation controller. The view that I am returning to will need to use that array.

I have read that you should not invoke the synchronize method manually for performance reasons and that NSUserDefaults will write the data periodically. However, can I be certain the array will always be updated for the view to use on back button press?

The array needs to be permantely stored as well which is why I am using NSUserDefaults

james
  • 2,595
  • 9
  • 43
  • 70

1 Answers1

1

You could call synchronize() but need to be aware of the following wrinkle it has.

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.

Link

In your scenarios, you should call it since you are making changes and system may not trigger the synchronize() method in time and your check might not be valid when coming back to the view controller on back press.

Another approach that I could suggest would be to declare a global array, maybe in App Delegate and set and fetch values to that.

Now when the app is about to terminate, in applicationWillTerminate just save this global array in user defaults, call synchronize() and similarly when app is about launch, fetch the values from user defaults and set the values to your global array.

This way you need to call synchronize() just once and you will also have latest copy of the data as well.

Umar Farooque
  • 2,049
  • 21
  • 32