5

I've been searching for a while, do I need to do synchronize if I am doing:

[[NSUserDefaults standardUserDefaults] removeObjectForKey:kType];

After that, should I do?:

[[NSUserDefaults standardUserDefaults] synchronize];

Waiting for you answers in this matter.

dan
  • 9,695
  • 1
  • 42
  • 40
ZetaPR
  • 964
  • 7
  • 32

1 Answers1

5

Quoting this post in stackoverflow, the answer from DarkDust:

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 where 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.

Community
  • 1
  • 1
ZetaPR
  • 964
  • 7
  • 32
  • What happens if you write to defaults, don't synchronize, and sometime after your app crashes. I believe in that case you will lose your changes. So is it best to always synchronize after a write? – lostintranslation May 31 '17 at 13:48
  • 1
    Unless that the data you are storing into the defaults is very important, yes you will lose it. But this should never happen as you are not suppose to store data that is important and all of it should be created again, you have to handle in a different way. Like the quote said about the documentation the purpose of synchronize is to write immediately to disk and that is usually handled by the OS in appropriate moments. – ZetaPR Jun 01 '17 at 14:42