I wouldn't over-complicate it just yet. Add a print
statement every time you write to or read from the defaults. It might be that you're wiping out a value accidentally.
I was getting a similar issue because I had spelled a key wrongly. I was writing "events" and reading "evetns" in one place. Changed to using constants (let kEvents: String = "events"
etc.), and everything is fine; no opportunity for typos.
I also created set and get functions for the UserDefaults:
func settingsSet(_ value: Any, forKey key: String) {
UserDefaults(suiteName: kAppGroup)?.set(value, forKey: key)
UserDefaults(suiteName: kAppGroup)?.synchronize()
}
func settingsGetBool(forKey key: String, withFallback fallback: Bool) -> Bool {
guard let value = UserDefaults(suiteName: kAppGroup)?.object(forKey: key) else { return fallback }
return value as? Bool ?? fallback
}
// ... repeat for Int, String, Date...
// Then, each individual setting has functions like this:
func settingsSetUseImages(_ value: Bool) {
settingsSet(value as Bool, forKey: kSettingsUseImages)
}
func settingsGetUseImages() -> Bool {
return settingsGetBool(forKey: kSettingsUseImages, withFallback: true)
}
// Usage:
settingsSetUseImages(true) // Set to true
let useImages = settingsGetUseImages() // Get current value, and if not set, return `fallback` of true
You can add a print
statement to the defaultsSet
function to write out what value is being set for which key.
By abstracting that out you can also replace the means of storing settings values later on without having to change any of the instances of where you're actually updating/reading those values.
Hope this helps. Might be overkill for your issue, but it helped me :)