13.11 · Keychain status codes, detecting corruption, an LRU cache and library trade-offs
What happens when storage goes wrong or is shared: how you detect damage, how the Keychain reports state, how a cache evicts, and which engine to pick.
Mental model. Storage code is mostly error handling: handle each status, verify what you read, and decide who owns the file.
Verifying and caching
Keychain statuses and upsert, integrity checks and an LRU cache.
- Which OSStatus values matter when you use SecItem functions, and how do you write a correct save (upsert) of a secret?
The Keychain API returns an OSStatus for everything, and the useful values are few. errSecSuccess (0); errSecDuplicateItem (−25299) when SecItemAdd finds an… - How do you detect a damaged database or file, and what do you do about it?
Corruption is rare but real (a full disk, a bad write, a failing storage controller, a copy of a WAL database without its log, a bug). Detect it at three… - Implement an LRU cache with O(1) get and set: which data structures, and what does the eviction order look like?
A least-recently-used cache needs two operations in constant time: find an entry by key, and move an entry to the “most recent” position or remove the “least…
Choosing
Core Data versus SwiftData versus GRDB versus Realm.
- Core Data, SwiftData, GRDB, SQLite.swift or Realm: how do you choose, and what do you give up with each?
Choose by what you need to control. Core Data is the mature object-graph framework: lazy loading, change tracking, undo, migrations, CloudKit mirroring…
More in Persistence & data
- 13.1 · Where data belongs, and the Keychain
- 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