MA4: App architecture, state and storage on the phone
Saving reliably and changing the format
🎯You'll be able to
Save data so it can't be half-written or overtaken, read it back safely, and change the stored format between app versions.
🏠The everyday picture
A shop's ledger has a page for each day, written in order. When the shop changes its columns next year, it doesn't rewrite old pages; it starts a new format and knows how to read both.
📘What it really is
- Write in order: chain saves so each finishes before the next starts, or a slow early save can overwrite a newer one.
- Write whole snapshots (or use a database transaction), so a crash can't leave half a record.
- Flush: offer a way to wait until everything is written, for tests and before risky moments.
-
Read safely: if stored data can't be read (corrupt or from a future version), don't crash; start clean or recover what you can, and report it.
-
Version the format: include a version in the key or the data (
khetnote:v1). When the shape changes, write a migration that reads v1 and writes v2, once.
📝A worked example
Input: KhetNote 1.2 will add a followUp date to visits and rename issue to reported.
Steps:
- Keep reading
khetnote:v1. On start, if it exists andkhetnote:v2doesn't, convert each visit and write v2. - Keep v1 until v2 is written successfully, then remove it.
- Test: a store with v1 data opens in 1.2 with every visit intact.
Expected output: an upgrade that keeps every adviser's data.
🌍Where it's used
- Every app update that changes stored data needs a migration.
- Databases on phones (SQLite, Room, Core Data) have migration tools.
- Crash reports often trace back to unreadable stored data after an update.
📝Case scenario
A notes app changed its storage format without a migration. After the update, it couldn't read old notes and showed an empty list. Many users thought their notes were deleted. A hotfix added the migration, but the reviews stayed.
🖱️Try it
Write the steps of a v1-to-v2 migration for one change to KhetNote's data, and the test you'd write for it. Success: your steps keep v1 until v2 is safely written.
⚠️Common mistakes
- Saves that overtake each other. Sign: older data after quick changes. Fix: chain writes in order.
- Crashing on bad data. Sign: the app won't open after an update. Fix: read carefully and recover.
- Changing the format without a migration. Sign: empty screens after updating. Fix: version and migrate.
🛠️For your project
Project 1's store saves in order and offers flush(); tests 1, 3 and 8 restart the store and expect the data, outbox and cursor back.
✅Quick check
Why chain saves one after another?
Show the answer
So a slow earlier save can't overwrite a newer one.
What should a migration keep until the new format is safely written?
Show the answer
The old data.
