What are UserDefaults?

UserDefaults are used to save small pieces of data in the application. It can be used to save the application's settings, some flags, or user tokens. The UserDefaults is a property list file in the application package.

It stores data as the key-value pairs (dictionary); therefore, userdefaults is considered as the Key-Value-Store (KVS). The UserDefaults is the instance of the UserDefaults class provided by Apple. It was formerly known as NSUserDefaults.

The UserDefaults is declared as below.

Internally, the UserDefaults are stored as a property list file in the column-row format. It is similar to the info.plist file stored in the application's package, which contains the information about the application like bundle identifier, ATS settings, build version, and a lot more.

The Info.plist file looks like the following image.

Saving Data in UserDefaults

The perfect example of Userdefaults is the user token that we store in it for every application. Just think of an application that requires the user to login every time into the app being used. It becomes very irritating for the user to login every time into the app. Instead, we can store the user token in userdefaults once we successfully hit the login API on the server. However, the data in the userdefaults will be destroyed once the application is uninstalled from the device.

Saving Data in the UserDefaults

In UserDefaults, we can store a number of data types like Boolean, Integer, String, and Float. We can also store the binary data with Data, dates with Date, URLs with the URL data type. We can also store Array and Dictionary into the UserDefaults.

To save the data in the UserDefaults, first, we need to get the reference to the UserDefaults by using the standard property.

The following code can be used to save a string in the UserDefaults.

Internally, we are creating a key-value pair where we are assigning the value token to the key userToken.

Here, we can also overwrite the value that is previously saved. For the above code, if we store another value for userToken, the previous value will be removed from the UserDefaults.

To remove any value from the UserDefaults, the removeObject() method is used. Here, we want to remove the value for key userToken, we can write the following code.

The UserDefaults are cached in the iPhone's memory. It remains there until the app remains running.






Latest Courses