Search code examples
iosnsuserdefaultsuserdefaults

Do I have to use standard shared UserDefaults object?


As a convention, when dealing with UserDefaults, we use the standard object of it. However, using the standard UserDefaults should set/get values that are accessible from a new instance and vise versa. To clarify:

let object = UserDefaults()
object.set(101, forKey: "number1") // setting via a new object
UserDefaults.standard.integer(forKey: "number1") // getting via standard
// 101

UserDefaults.standard.set(102, forKey: "number2") // setting via standard
object.value(forKey: "number2") // getting via the new object
// 102

I would assume that standard is not exists as "syntactic sugar", it doesn't seem to be sensible to create a singleton class just for this purpose.

So:

  • Is there benefit(s) of using standard instead of UserDefaults()? If there is, what is it? Could it be related to the suites?
  • If there is something behind it, why are we even able to declare UserDefaults()?

Solution

  • Calling UserDefaults() is the same as calling UserDefaults(suiteName: nil).

    Calling UserDefaults(suiteName: nil) returns an object that behaves like UserDefaults.standard:

    If you pass nil to this parameter, the system uses the default search list that the standard class method uses.

    So there is no advantage in using UserDefaults() instead of UserDefaults.standard.

    The advantage of using UserDefaults.standard instead of UserDefaults() is that only a single UserDefaults.standard object exists, so it may be faster and may use less memory to use UserDefaults.standard than to create a new object by calling UserDefaults().