Member-only story
What are various ways to persist data in iOS?
3 min readDec 9, 2022
There are several ways to persist data in iOS, each with its own benefits and trade-offs. Some of the most common ways to persist data in iOS are:
- UserDefaults: UserDefaults is a simple key-value store that allows you to save small amounts of data, such as user preferences or settings. To save a value in UserDefaults, you can use the
set
method, like this:
let userDefaults = UserDefaults.standard
userDefaults.set("value", forKey: "key")
To retrieve a value from UserDefaults, you can use the value(forKey:)
method, like this:
let userDefaults = UserDefaults.standard
if let value = userDefaults.value(forKey: "key") as? String {
print(value) // Prints "value"
}
- Keychain: The Keychain is a secure store for sensitive data, such as passwords or cryptographic keys. To save a value in the Keychain, you can use the
SecItemAdd
function from the Security framework, like this:
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "key",
kSecValueData as String: "value".data(using: .utf8)!
]
let status = SecItemAdd(query as CFDictionary, nil)
To retrieve a value from the Keychain, you can use the SecItemCopyMatching
function, like this: