Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to do synchronize in NSUserDefaults after removing object from keys?

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.

like image 578
ZetaPR Avatar asked Jun 07 '16 13:06

ZetaPR


People also ask

Where NSUserDefaults data is saved?

The user's defaults database is stored on disk as a property list or plist. A property list or plist is an XML file. At runtime, the UserDefaults class keeps the contents of the property list in memory to improve performance. Changes are made synchronously within the process of your application.

What is UserDefaults standard synchronize?

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.

Which method is used to remove all keys from user default?

To remove a key-value pair from the user's defaults database, you need to invoke removeObject(forKey:) on the UserDefaults instance. Let's update the previous example. The output in the console confirms that the removeObject(forKey:) method works as advertised.

How does NSUserDefaults work?

NSUserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. When you set a default value, it's changed synchronously within your process, and asynchronously to persistent storage and other processes.


1 Answers

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.

like image 97
ZetaPR Avatar answered Nov 15 '22 08:11

ZetaPR