Getting Data from UserDefaults

Getting data from UserDefaults is very simple. The following methods are used as the getter methods in UserDefaults.

SNMethodDescription
1func object(forKey: String) -> Any?It returns the object associated with the specified key.
2func url(forKey: String) -> URL?It returns the url associated with the specified key.
3func array(forKey: String) -> [Any]?It returns the array associated with the specified key.
4func dictionary(forKey: String) -> [String : Any]?It returns the dictionary associated with the specified key.
5func string(forKey: String) -> String?It returns the string associated with the specified key.
6func stringArray(forKey: String) -> [String]?It returns the string array associated with the specified key.
7func data(forKey: String) -> Data?It returns the binary data associated with the specified key.
8func bool(forKey: String) -> BoolIt returns the boolean value associated with the specified key.
9func integer(forKey: String) -> IntIt returns the integer value associated with the specified key.
10func float(forKey: String) -> FloatIt returns the float value associated with the specified key.
11func double(forKey: String) -> DoubleIt returns the double value associated with the specified key.
12func dictionaryRepresentation() -> [String : Any]It returns the dictionary representation of the UserDefualts.

Since the UserDefaults use the data types to retrieve the value stored associated with the key. However, the value for the specified key might not exist. Hence, we need to use the optional binding while retrieving the value from the UserDefaults.

In real-time projects, we use UserDefaults in a singleton Shared Preference class. Let's consider the following example where we create an explicit SharedPreferenceManager class and put all the code related to user defaults there.

SharedPreferenceManager.swift

ViewController.swift

The SharedPreferenceManager class can be used in a real-time project where we can put all the setter and getter methods to save and retrieve values from UserDefaults.

Where to use UserDefaults

The UserDefaults are mainly used to store simple pieces of data. However, If we need to store multiple objects of the same type, it's better to use an actual database, like CoreData or SQLite. Database design is an important aspect of the architecture of your app. We will learn CoreData in the next section of this tutorial.

Use Cases of using UserDefaults

  1. We can store user information like name, email address, age, or occupation in UserDefaults.
  2. We can store the navigation flags which can be checked in AppDelegate, and the user is navigated based upon the flags saved in UserDefaults.
  3. Application Settings like interface language, color theme, etc. can be stored in UserDefaults.
  4. We can store the user access token in the UserDefaults.

Next TopicCoreData




Latest Courses