CS50 iOS Track 5: Saving Data in iOS Apps with SQLite

Jun 14, 2024

Lecture Notes: Saving Data in iOS Apps with SQLite

Introduction to SQLite

  • SQLite is a simple SQL database used in iOS apps to save data.
  • Queries are written in Swift to persist data to disk.
  • Data can be read back when users reopen the app.

Basic SQL Queries in SQLite

  • CREATE Query: Creates tables

    • Example: CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)
    • id is an INTEGER, PRIMARY KEY, AUTOINCREMENT.
    • name is a TEXT field for user names.
  • INSERT Query: Inserts data into tables

    • Example: INSERT INTO users (name) VALUES ('Tommy')
  • SELECT Query: Reads data from tables

    • Example: SELECT * FROM users WHERE name = 'Tommy'
  • UPDATE Query: Updates existing data in tables

    • Example: UPDATE users SET name = 'Tommy M' WHERE name = 'Tommy'

Example App: Notes App

  • Simple Notes App to create, read, save, and browse notes using SQLite.

Setting Up Xcode Project

  1. Create a new Xcode project named 'Notes'.
  2. Use the storyboard to set up the initial views.
    • Use a TableViewController for the main screen showing notes.
    • Use a second ViewController for the note detail view.
  3. Embed a Navigation Controller.
  4. Customize the table view cells and navigation.

Creating the Model

  1. Define a Note Struct
    • struct Note { var id: Int, var contents: String }
  2. Create NoteManager Class
    • Manages database connections, reads, updates, and creates notes.

Connecting to SQLite

  1. Database Path Setup
    • Use FileManager to get the database URL.
    • Ensure the database file and its directory exist.
  2. Database Connection
    • Use sqlite3_open to connect.
  3. Creating Tables
    • Use sqlite3_exec to execute SQL commands.

CRUD Operations

  1. Create Note
    • Prepare and execute INSERT statement, bind parameters.
  2. Get All Notes
    • Prepare and execute SELECT statement, read data in a loop.
  3. Save Note
    • Prepare and execute UPDATE statement, bind parameters.

Integrating Model with ViewControllers

  1. Passing Data
    • Use prepare(for:sender:) to pass data between view controllers.
  2. Reload Data on Return
    • Use viewWillAppear to refresh data when returning to the main view.
  3. Editing and Saving Notes
    • Handle text view data binding and call save methods on note updates.

Adding User Interface Elements

  • Add UI elements like buttons, text views, and labels.
  • Set up constraints for UI elements to fit different screen sizes.

Final Testing

  • Run the app to ensure notes are created, saved, and displayed correctly.