0
0
iOS Swiftmobile~20 mins

Core Data overview in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Core Data Sample Screen
This screen shows a list of simple notes saved using Core Data. Users can add new notes and see them appear in the list.
Target UI
-------------------------
| Core Data Notes       |
|-----------------------|
| + Add Note            |
|-----------------------|
| - Note 1              |
| - Note 2              |
| - Note 3              |
|                       |
-------------------------
Display a list of saved notes from Core Data
Add a '+' button in the navigation bar to add a new note
When '+' is tapped, show an alert with a text field to enter note text
Save the new note to Core Data and update the list
Use Core Data stack with NSPersistentContainer
Fetch notes using NSFetchRequest
Use SwiftUI List to show notes
Starter Code
iOS Swift
import SwiftUI
import CoreData

struct ContentView: View {
    // TODO: Add @Environment for managedObjectContext
    // TODO: Add @FetchRequest for notes

    @State private var showingAddNote = false
    @State private var newNoteText = ""

    var body: some View {
        NavigationView {
            List {
                // TODO: Show notes here
            }
            .navigationTitle("Core Data Notes")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        showingAddNote = true
                    }) {
                        Image(systemName: "plus")
                    }
                }
            }
            // TODO: Add alert for adding note
        }
    }
}

@main
struct CoreDataApp: App {
    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}

// TODO: Add PersistenceController class here
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
iOS Swift
import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var context
    @FetchRequest(
        entity: Note.entity(),
        sortDescriptors: [NSSortDescriptor(keyPath: \Note.timestamp, ascending: true)]
    ) private var notes: FetchedResults<Note>

    @State private var showingAddNote = false
    @State private var newNoteText = ""

    var body: some View {
        NavigationView {
            List {
                ForEach(notes) { note in
                    Text(note.text ?? "No Text")
                }
            }
            .navigationTitle("Core Data Notes")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        showingAddNote = true
                    }) {
                        Image(systemName: "plus")
                    }
                }
            }
            .alert("Add New Note", isPresented: $showingAddNote, actions: {
                TextField("Note text", text: $newNoteText)
                Button("Save") {
                    addNote()
                }
                Button("Cancel", role: .cancel) { }
            })
        }
    }

    private func addNote() {
        let newNote = Note(context: context)
        newNote.timestamp = Date()
        newNote.text = newNoteText

        do {
            try context.save()
            newNoteText = ""
        } catch {
            print("Failed to save note: \(error)")
        }
    }
}

@main
struct CoreDataApp: App {
    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}

class PersistenceController {
    static let shared = PersistenceController()

    let container: NSPersistentContainer

    init() {
        container = NSPersistentContainer(name: "CoreDataModel")
        container.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Core Data store failed: \(error)")
            }
        }
    }
}

// Core Data Note entity class is generated automatically from model with attributes:
// - text: String?
// - timestamp: Date?

This app uses SwiftUI with Core Data to save and display simple notes.

We use @Environment(\.managedObjectContext) to access Core Data context.

@FetchRequest fetches Note entities sorted by timestamp.

The list shows all saved notes.

Tapping '+' shows an alert with a text field to enter a new note.

Saving creates a new Note object, sets its properties, and saves the context.

PersistenceController sets up the Core Data stack with NSPersistentContainer.

This structure keeps UI and data management clean and simple for beginners.

Final Result
Completed Screen
-------------------------
| Core Data Notes       |
|-----------------------|
| + Add Note            |
|-----------------------|
| - Buy groceries       |
| - Call mom            |
| - Walk the dog        |
|                       |
-------------------------
Tap '+' button to open alert with text field
Enter note text and tap Save to add note
New note appears in the list immediately
Tap Cancel to close alert without saving
Stretch Goal
Add swipe-to-delete functionality to remove notes from the list and Core Data.
💡 Hint
Use .onDelete modifier on the List and call context.delete() followed by context.save() to remove notes.