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?