project habittracker

Step 5: Persistence

System Text-to-Speech Ready
Slide: 0:00 / 0:00
Slide 1 of 0Interactive Deck

Full Lesson Reference

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

terminal
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

terminal
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

  1. Run the app
  2. Add some habits and check a few off
  3. Stop the app completely (Cmd + Q in simulator)
  4. Run again
  5. Your habits and completions should still be there

Add Delete

Now that data persists, users need a way to remove habits:

terminal
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

Exercises

  1. Add Codable support and the persistence layer, then do the full restart test: add habits, check some off, quit with Cmd + Q, relaunch, and confirm everything is still there.
  2. Add swipe-to-delete, remove a habit, restart the app, and verify it stays deleted.
  3. Ask Claude where the JSON file lives in the documents directory, then have it print the saved JSON so you can see exactly how your habits are stored.