NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:@"xxxxxxxx" forKey:@"name"]; [defaults synchronize];
I need to know why do i have to use the last line of the above code [defaults synchronize]
? What is the purpose of using it? Is it a must ?
NSUserDefaults automatically persists the dictionary to a file every once in a while. The only reason there is a synchronize method is so your app can tell NSUserDefaults to persist the dictionary "now" instead of waiting for the automatic saving that will eventually happen.
Writing or Setting Values To User Defaults You simply invoke the set(_:forKey:) method on the UserDefaults instance. In this example, we set the value of myKey to true by invoking the set(_:forKey:) method on the shared defaults object.
The purpose of [default synchronize];
is to make the user defaults get written on disk immediately. You don't need to call it explicitly, iOS already does it at appropriate moments. So you can remove that line. In fact, it's a performance problem if you call synchronize
every time you set a default.
Prior to iOS 7, the user defaults were always synchronized when the application transitioned into background. As of iOS 7, that is no longer the case, so you might want to call synchronize
in your app delegate's applicationDidEnterBackground:
or register to the UIApplicationDidEnterBackgroundNotification
notification to do that.
From the documentation for -[NSUserDefaults synchronize]
:
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.
You don't have to write that line anymore.
The method reference from the updated documentation
Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used.
Comments to the method explaining what to do.
/*! -synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release. -synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized... - ...before reading in order to fetch updated values: remove the synchronize call - ...after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify - ...before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication) - ...for any other reason: remove the synchronize call */ open func synchronize() -> Bool
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With