Is it mandatory to call NSUserDefaults synchronize method? Is it mandatory to call NSUserDefaults synchronize method? ios ios

Is it mandatory to call NSUserDefaults synchronize method?


No.

Since iOS12, it isn't mandatory anymore.Apple says:

This method is unnecessary and shouldn't be used.

You can find more information on iOS12 release note:

UserDefaults

NSUserDefaults has several bug fixes and improvements:

Removed synchronization requirements. It's no longer necessary to use synchronize, CFPreferencesAppSynchronize, or CFPreferencesSynchronize. These methods will be deprecated in a future version of the OS.

Now that you don't need to call these synchronization methods, the performance characteristics of NSUserDefaults and Preferences Utilities are slightly different: The time taken for enqueueing write operations is now paid by the writing thread, rather than by the next thread to call synchronize or do a read operation.


From the docs:

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.

Meaning that if you kill the app right after something is written to the defaults without the periodic interval catching it, it will get lost. You probably did not kill the app right after a write event yet which is why your app seems to work fine so far.


Normally it works perfectly fine and you only have to use it in special cases, for example when the app will close directly after writing to NSUserDefaults. So you can simply add the synchronize method to the corresponding AppDelegate-method.