13.1 · Where data belongs, and the Keychain
Persistence starts with a decision: what is this data, and what must happen to it when the app is deleted, restored or the device is lost? The wrong container is a bug even if the code is perfect.
Mental model. Pick the store by the data’s lifetime and sensitivity, not by what is convenient: secrets to the Keychain, user data to a database or files, rebuildable data to caches.
Choosing
The storage options and what survives what.
- UserDefaults, Keychain, files, SQLite, Core Data or SwiftData: how do you choose, and what survives deletion, reinstall and backup?
Start with what the data is. Preferences and small flags (a theme, the last tab) go to UserDefaults (a property list in the app container; fast and simple, but…
Secrets
Keychain items, attributes and accessibility.
- How does the Keychain work, how do you add, read and update an item, and what do accessibility classes and access groups do?
The Keychain is an encrypted database managed by the system, accessed through the C SecItem API with dictionaries of attributes. An item belongs to a class…
More in Persistence & data
- 13.2 · SQLite fundamentals: transactions, WAL, constraints, indexes and migrations
- 13.3 · The Core Data stack, contexts and faults, concurrency, and migrations
- 13.4 · SwiftData: models, contexts, predicates, actors and schema evolution
- 13.5 · The repository pattern and cache design
- 13.6 · Crashes mid-write, integrity, backups and data protection
- 13.7 · Syncing data across devices: conflicts, tombstones and CloudKit
- 13.8 · UserDefaults surprises and FileManager essentials
- 13.9 · Reading query plans, typing and NULL, WAL locking, savepoints and full-text search
- 13.10 · Merge conflicts, faults and batch requests, delete rules, and the SwiftData context
- 13.11 · Keychain status codes, detecting corruption, an LRU cache and library trade-offs