NSUserDefaults synchronize-method

2019-01-01 07:40发布

问题:

 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 ?

回答1:

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.



回答2:

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


回答3:

Yes, with that line you are telling your system to upload the NSUserDefaults with your new defaults.

You can find all the information here:

  • https://developer.apple.com/documentation/foundation/nsuserdefaults
  • https://developer.apple.com/documentation/foundation/nsuserdefaults/1414005-synchronize