iOS UserDefaults

Saving Data in Userdefaults

What are UserDefaults?

Small amounts of data are saved in the application using user defaults. It can be used to store user tokens, some flags, and application settings. Within the application package is a property list file called UserDefaults.

Userdefaults is regarded as the Key-Value-Store (KVS) since it saves data as key-value pairs (dictionaries). The UserDefaults is the Apple-provided instance of the UserDefaults class. Before, it was called NSUserDefaults.

As stated below, the UserDefaults are declared.

				
					class UserDefaults : NSObject  
				
			

The UserDefaults are internally kept in a column-row manner as a property list file. It resembles the info.plist file found in the application package, which has a wealth of information about the application, including the bundle identifier, build version, ATS settings, and many other details.

The following image depicts how the Info.plist file appears.

Saving Data in Userdefaults -

The user token we save in it for each application is the ideal illustration of Userdefaults. Imagine using an app that needs the user to log in each time they want to use it. The user finds it increasingly annoying to have to check in to the app each time. Instead, after we successfully call the server’s login API, we may save the user token in userdefaults. However, if the application is removed from the device, the data in the userdefaults will be lost.

Saving Data in the UserDefaults

We can store a variety of data types, including Boolean, Integer, String, and Float, in UserDefaults. Additionally, we can store dates with Date, binary data with Data, and URL data types with URL. Dictionary and Array can also be kept in the UserDefaults.

Prior to saving the data in the UserDefaults, we must use the standard property to obtain a reference to the UserDefaults.

				
					UserDefaults.standard  
				
			

To store a string in the UserDefaults, use the code below.

				
					let token = "ABCDEFGD!@#$456MK"  
UserDefaults.standard.set(token, forKey: "userToken")  
				
			

Internally, we’re assigning the value token to the key userToken in order to create a key-value pair.

				
					{  
"userToken" : "ABCDEFGD!@#$456MK"  
}  
				
			

We have the option to overwrite the previously saved value here as well. If we store a different value for userToken in the code above, the prior value will be eliminated from the UserDefaults.

The removeObject() method is used to delete any value from the UserDefaults. Here, we wish to delete the value for the userToken key. To do this, we can write the code that follows.

				
					UserDefaults.standard.removeObject(forKey : "userToken ")  
				
			

The iPhone stores the UserDefaults in a cache. It stays there as long as the application is still open.

Share this Doc

Saving Data in Userdefaults

Or copy link

Explore Topic