First of all, let me say that this is NOT a complaint, I just want to understand how does the register(defaults: [])
method works.
I'm using the UserDefaults register(defaults: [])
method inside the didFinishLaunchingWithOptions
method to register the default value of all of my UseDefault keys, everything is working fine as expected.
My question is, why is that the values in the register(defaults: [])
method do not reset everytime the didFinishLaunchingWithOptions
method is called?
I do not want them to rest I'm just trying to understand why.
I have the following code...
func application(...didFinishLaunchingWithOptions...) -> Bool {
UserDefaults.standard.register(defaults: [
keyUserName:"",
keyHasCar:false
])
}
Here is why my confusion, when the app runs, it saves the default values as expected, then, if the values get modified later somewhere in the app and right-after the app is killed and relaunched, the didFinishLaunchingWithOptions
is called again but the values do not get reset, but if I add a new key to the array it does get saved but the rest of the keys do not get reset only the new one is added with its default value.
Again, I do not want the values to reset, I just need to understand how does register
method works.
From the documentation for
register(defaults:)
:What this means is that the registered defaults act as a fallback to the normal, user defaults that you are working with. The registered defaults do not overwrite or replace the standard user defaults.
When you attempt to lookup a key from
UserDefaults.standard
, if the key isn't there, then it is looked up in the registered defaults and that result (if any) is returned.Once you set a value in
UserDefaults.standard
, of course it is that value that is returned for the key. If you remove the key fromUserDefaults.standard
then the registered default is used again.