0

I am developing a Mac application that is currently configured with UserDefaults. I would like to be able to swap it out with JSON configuration in the future.

Here's the problem - UserDefaults reads/writes on a per-key basis, whereas with JSON you read/write the configuration in bulk (as a single file).

The simple solution would be create a protocol with the lowest common denominator - write/read disk in bulk:

protocol PreferencesRepository {
  read() -> Preferences
  readLive() -> Observable<Preferences>
  write(Preferences)
}

struct Preferences {
  let configA: String
  let configB: String
  ...
}

The implementation of PreferencesRepository when using UserDefaults would look like this:

read() -> Preferences {
  let a = userDefaults.read("keyA")
  let b = userDefaults.read("keyB")
  ...
  return Preferences.init(a, b, ...)
}

write(preferences: Preferences) {
  userDefaults.write("keyA", preferences.configA);
  userDefaults.write("keyB", preferences.configB);
  ...
}

You can see how if just one property of Preferences changes, all properties will be written to UserDefaults.

I understand that UserDefaults has optimizations to avoid reading from disk as much as possible by keeping an in-memory cache in sync with the disk. Does UserDefaults use that same cache to avoid redundant writes?

Dexter Leng
  • 71
  • 1
  • 2
  • 7
  • *Does UserDefaults use that same cache to avoid redundant writes?* - yes, it does. You can think that it's performed regularly on your behalf, but you can force `synchronize` whenever needed (however this is not recommended). – Asperi Dec 17 '20 at 05:04
  • Not only is `synchronize` not recommended. It doesn't work. https://stackoverflow.com/questions/16861142/nsuserdefaults-synchronize-not-saving-on Rather than fix the function, Apple deprecated it. – Daniel T. Mar 27 '21 at 22:06

0 Answers0