Home > Back-end >  Determine if a UserDefault property has been set, or if the value returned for a property is a regis
Determine if a UserDefault property has been set, or if the value returned for a property is a regis

Time:08-04

I am using UserDefaults to store my app preferences. Upon initialization the preference properties and values are created, the defaults object is initialized using a suite name (my app name), and then I convert my preferences to a dictionary and register the preferences in the defaults object.

What I would like to know is if I request defaults.object(forKey: "someKey") how can I know if that key has been set due to a preferences change, or it is a registered default value? I have read the documentation and I did not see anything that would allow me to determine that.

The dictionary created for the defaults is not persisted in memory, but I guess if needed to I could make it a global property and then compare the returned value to the dictionary value and if the values are them same I could assume the value is being returned from the registered defaults. I just wanted to ask before I make that code change.

CodePudding user response:

Rather than setting it to a default value. Could you wrap the user defaults and return the default value if it is not set. Only set the user defaults when the user sets it.

So now, if the user defaults value is nil. You can return your default value and know that it is the default.

If the user defaults value is not nil. You can return that value and know it is like that because the user set it. (Even if it happens to be the same as the default).

CodePudding user response:

if UserDefaults.standard.value(forKey: "KEY") != "DEFAULT VALUE" { 
 ///if not default value
} else {
   //default value
}

Hope this helps

  • Related