1️⃣Persistence

Fall 2023 | Vin Bui

Data persistence is the mechanism involving the storage of data on a disk without being altered by the user the next time the app is launched. In the iOS world, this primarily involves storing the data locally on the user’s device.

Why Persistence?

By default, the data that is allocated in our app is stored in RAM which is immediately cleared as soon as the user closes out of the app. For example, say we had an array of students displayed in a table view. Assuming there is no backend integration, when we launch the app, this array is stored locally in RAM. If we were to add a new student to this array during the app’s lifetime, we will notice that when we relaunch the app, the added student is gone.

Sometimes we want to save data on the user’s local disk so that when the user opens the app again, that data persists. The most common use for persistence in iOS is to store app settings or user preferences. For example, if the app is light mode by default, but the user wants it in dark mode, we need to make sure that this preference is saved so that in the next launch, the app will be in dark mode.

Examples of Persistence

In Swift, we can use the following tools and APIs to achieve data persistence:

  • UserDefaults

  • File System

  • Keychain

  • CoreData

  • SwiftData

  • Property Lists

In this course, we will only be looking at UserDefaults.

UserDefaults

UserDefaults allows us to store small pieces of data on a user’s local drive. Reading and writing to user defaults is very simple since it uses key-value pairs, just like a dictionary.

To write to UserDefaults, simply follow this format:

UserDefaults.standard.setValue(_ value: Any?, forKey key: String)

// For example, to store the string "Vin" for key "name", we can do...
UserDefaults.standard.setValue("Vin", forKey: "name")

To read from UserDefaults, follow this format:

UserDefaults.standard.string(forKey: String)
UserDefaults.standard.bool(forKey: String)
UserDefaults.standard.integer(forKey: String)
UserDefaults.standard.array(forKey: String)
UserDefaults.standard.dictionary(forKey: String)

// Using the example earlier, to access the value stored in key "name"...
UserDefaults.standard.string(forKey: "name") // Returns "Vin"
// Note that we use `.string` since we stored a String type for this key

One thing to keep in mind when reading from UserDefaults is the type of the returned value. For example, when reading in a String, we will receive a String? type.

You can also store custom objects in UserDefaults; however, that requires using an encoder/decoder. For the scope of this course, we will only store simple pieces of data.

Last updated