finneycanhelp
finneycanhelp

Reputation: 9248

Where Is Authoritative Source of Do Not Call NSUserDefaults synchronize for iOS 8 and Above?

I recall that one should not bother calling NSUserDefaults' synchronize method on iOS 8 and above. I also read from a one non-Apple source and another a hint of the same. However, I am having trouble finding an authoritative source from Apple. Was it a WWDC video from a couple years back? What was the Apple authoritative source?

Read this: NSUserDefaults and skimmed through some of this: WWDC 2014 Videos

Upvotes: 4

Views: 137

Answers (2)

Alex Pretzlav
Alex Pretzlav

Reputation: 15615

The most accurate source I've seen is the following tweet and blog post from David Smith, a developer at Apple who works on NSUserDefaults: https://twitter.com/catfish_man/status/674727133017587712 and http://dscoder.com/defaults.html

Reminder that the only thing -[NSUserDefaults synchronize] does is wait. That’s not useless, but the situations it’s useful in are uncommon.

The blog post elaborates:

If you find yourself to do anything else to set a preference, again, you probably don't need to. It is almost never necessary to call -synchronize after setting a preference (see Sharing Defaults Between Programs below), and users are generally not capable of changing settings fast enough for any sort of "batching" to be useful for performance. The actual write to disk is asynchronous and coalesced automatically by NSUserDefaults.

If one process sets a shared default, then notifies another process to read it, then you may be in one of the very few remaining situations that it's useful to call the -synchronize method in: -synchronize acts as a "barrier", in that it provides a guarantee that once it has returned, any other process that reads that default will see the new value rather than the old value. For applications running on iOS 9.3 and later / macOS Sierra and later, -synchronize is not needed (or recommended) even in this situation, since Key-Value Observation of defaults works between processes now, so the reading process can just watch directly for the value to change. As a result of that, applications running on those operating systems should generally never call synchronize.

Upvotes: 1

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

Well, after reading you comment (please add that link to your post) I came to this conclusion:

The article states you shouldn't call -[NSUserDefaults synchronize] because it is a performance drawback. I only use this when I really need the defaults to be written, for example when needing it up to date in a different class. I never felt like needing to.

To sum it up; better don't call it, for performance reasons. If you need the data to be up to date immediately, call it.

Upvotes: 2

Related Questions