Bird
Raised Fist0
iOS Swiftmobile~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of Core Data in an iOS app?
easy
A. To manage app animations
B. To store and manage app data on the device
C. To handle network requests
D. To design the app's user interface

Solution

  1. Step 1: Understand Core Data's role

    Core Data is used to save and manage data locally on the device.
  2. Step 2: Compare with other options

    UI design, network handling, and animations are handled by other frameworks, not Core Data.
  3. Final Answer:

    To store and manage app data on the device -> Option B
  4. Quick Check:

    Core Data = Data storage [OK]
Hint: Core Data is about data storage, not UI or network [OK]
Common Mistakes:
  • Confusing Core Data with UI frameworks
  • Thinking Core Data manages network calls
  • Assuming Core Data handles animations
2. Which class is used to set up Core Data stack easily in Swift?
easy
A. NSPersistentContainer
B. NSManagedObject
C. UIViewController
D. URLSession

Solution

  1. Step 1: Identify Core Data setup class

    NSPersistentContainer simplifies setting up Core Data stack.
  2. Step 2: Exclude unrelated classes

    NSManagedObject represents data, UIViewController manages UI, URLSession handles networking.
  3. Final Answer:

    NSPersistentContainer -> Option A
  4. Quick Check:

    Setup Core Data = NSPersistentContainer [OK]
Hint: NSPersistentContainer sets up Core Data stack [OK]
Common Mistakes:
  • Choosing NSManagedObject for setup instead of data model
  • Confusing UI or network classes with Core Data setup
  • Using outdated Core Data setup methods
3. Given this Swift code snippet, what type is 'person'?
let person = Person(context: context)
medium
A. An instance of NSManagedObject subclass
B. A UIViewController instance
C. A plain Swift struct
D. A network request object

Solution

  1. Step 1: Recognize 'Person' as NSManagedObject subclass

    In Core Data, entities are represented by NSManagedObject subclasses like Person.
  2. Step 2: Exclude other types

    UIViewController is for UI, struct is not used here, network object unrelated.
  3. Final Answer:

    An instance of NSManagedObject subclass -> Option A
  4. Quick Check:

    Core Data entity = NSManagedObject subclass [OK]
Hint: Core Data entities are NSManagedObject subclasses [OK]
Common Mistakes:
  • Thinking Person is a struct or class unrelated to Core Data
  • Confusing UI or network classes with data entities
  • Not recognizing Core Data context usage
4. What is wrong with this Core Data fetch request code?
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let results = try context.fetch(request) as? [Person]
print(results.count)
medium
A. NSFetchRequest cannot be used with context.fetch
B. Entity name "Person" is invalid
C. print(results.count) will cause a syntax error
D. Casting fetch results to [Person] may fail without specifying generic type

Solution

  1. Step 1: Analyze fetch request generic type

    Using NSFetchRequest<NSFetchRequestResult> returns generic results; casting to [Person] may fail.
  2. Step 2: Correct approach

    Use NSFetchRequest<Person> to get typed results and avoid unsafe casting.
  3. Final Answer:

    Casting fetch results to [Person] may fail without specifying generic type -> Option D
  4. Quick Check:

    Use typed NSFetchRequest to avoid cast issues [OK]
Hint: Use typed NSFetchRequest to avoid casting errors [OK]
Common Mistakes:
  • Ignoring generic type in NSFetchRequest
  • Assuming entity name is wrong without checking
  • Thinking context.fetch is invalid usage
5. You want to save a new 'Task' entity with a 'title' attribute using Core Data. Which sequence correctly saves the data?
hard
A. Create Task object, set title, call URLSession to save
B. Create Task object, set title, call print() to save
C. Create Task object, set title, call context.save() inside do-catch
D. Create Task object, set title, no need to save context

Solution

  1. Step 1: Create and set attributes on Task object

    Instantiate Task with context and assign the title attribute.
  2. Step 2: Save context with error handling

    Call context.save() inside a do-catch block to persist changes safely.
  3. Final Answer:

    Create Task object, set title, call context.save() inside do-catch -> Option C
  4. Quick Check:

    Save Core Data changes with context.save() [OK]
Hint: Always call context.save() inside do-catch to persist data [OK]
Common Mistakes:
  • Forgetting to call context.save() after changes
  • Using print or network calls to save data
  • Ignoring error handling when saving
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard