2 min read
Step 5: Persistence
Save data between app launches.
Where We Are
The app works, but data disappears when you restart. Let’s fix that.
Why Persistence Matters
Right now, all habits live in memory. Close the app and they’re gone. Real apps save data.
Add Codable Support
Make the Habit model conform to Codable so it can be saved and loaded.
This lets Swift convert habits to JSON and back.
Save and Load
Create a simple persistence layer that:
- Saves the habits array to a JSON file in the app's documents directory
- Loads habits from the file when the app starts
- Saves automatically whenever habits change (add, delete, toggle)
Use Swift's FileManager and JSONEncoder/JSONDecoder.
Test It
- Run the app
- Add some habits and check a few off
- Stop the app completely (Cmd + Q in simulator)
- Run again
- Your habits and completions should still be there
Add Delete
Now that data persists, users need a way to remove habits:
Add swipe-to-delete on habit rows.
When a habit is deleted, remove it from the list and save.
Checkpoint
By now you should have:
- Data persists between launches
- Habits can be deleted
- Completions and streaks survive restarts
What You Learned
- JSON encoding/decoding in Swift
- File system storage on iOS
- Codable protocol
- Automatic saving patterns