Is there a difference between UserDefaults()
and UserDefaults.standard
in Swift 3.0?
Asked
Active
Viewed 2,172 times
5

rolling_codes
- 15,174
- 22
- 76
- 112
2 Answers
12
UserDefaults - Gives you a new object
, each object is allocated a different memory and deallocated when object scope is finished.
UserDefaults.standard - Gives you the singleton
object by using the class method standard
the object received by this method is allocated single memory throughout the application.
And the usage of them if you´re interesedted in that:
// Set
UserDefaults.standard.set("YOUR STRING", forKey: "key")
UserDefaults().set("YOUR STRING", forKey: "key")
// Get
UserDefaults.standard.string(forKey: "key")
UserDefaults().string(forKey: "key")

Rashwan L
- 38,237
- 7
- 103
- 107
-
1Yeah.. but from a practical standpoint, how are they different? – Eric33187 Jul 20 '21 at 23:40
0
let ud = UserDefault()
let uds = UserDefaults.standard
- Both objects will use the same underlying plist file to get/set values.
- Setting a value for a key with "ud" gives the same value using the "uds" object.
You can create and use instances of "UserDefault" created with the convenience "init" method, but the Foundation documentation encourages a developer to use the singleton accessible by the "standard" variable.

Blazej SLEBODA
- 8,936
- 7
- 53
- 93