UserDefaults
As per Apple’s Documentation, UserDefaults
is
An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.
What type of data can we store in UserDefaults?
A default object must be a property list — that is, an instance of (or for collections, a combination of instances of)
NSData
,NSString
,NSNumber
,NSDate
,NSArray
, orNSDictionary
. If you want to store any other type of object, you should typically archive it to create an instance of NSData.
What does “A default object must be a property list” means?
You may have previously seen a .plist file before, plist stands for property list. There is usually an info.plist file created for you when you start new iOS project. When you store data in UserDefaults, the data format is similar to Info.plist as well. The UserDefaults plist is saved in the Library folder inside the app folder.
Adding, Reading and Removing values from UserDefaults
The shared defaults object
is utilised by the majority of applications. The API of the UserDefaults
class is easy to use in Swift. The most basic API to read or get values from the user's defaults database in Swift is object(forKey:)
. This method returns a value of type Any?
, which is optional. As previously stated, the defaults database is a key-value store. The UserDefaults class looks up the value for the key passed to the object(forKey:) function and returns a value if one exists. If no value exists for the provided key, it returns nil.
Creating or updating a key-value pair is simple. Just simply invoke set(_:forKey:)
method on the UserDefaults
instance. In this example, we set the value of theme
to light
by invoking the set(_:forKey:)
method on the shared defaults object.
In the documentation, Apple mentioned few example use cases. For example, you can allow users to specify their preferred units of measurement or media playback speed. Apps store these preferences by assigning values to a set of parameters in a user’s defaults database.
You can also use UserDefaults for storing user settings (eg: settings page in your app with UISwitch, Segmented Control or simple Textfield or, store non-sensitive data such as high score for a game, recently played song etc.
⚠️ The UserDefault class loads the contents of the property list once into memory when your app launches to improve performance and writes any changes you make to disk. Thus, avoid storing large amount of data into UserDefaults as it can affect performance of your app significantly.
Last updated
Was this helpful?