SwiftUI Core Data

SwiftUI Core Data

While FileManager is great for simple files, it is inefficient for managing thousands of complex, interconnected data records.

For heavy data management, Apple provides Core Data, a powerful, high-performance object graph and persistence framework.

Core Data is essentially an advanced database system built directly into iOS and macOS.


The Core Data Stack

To use Core Data, you first need a visual Data Model file (.xcdatamodeld) in Xcode where you define your Entities (tables) and Attributes (columns).

Next, you initialize the Core Data stack using an NSPersistentContainer.

Setting up the Container:

import CoreData

class DataController: ObservableObject { // Load the "MainModel" file from Xcode let container = NSPersistentContainer(name: "MainModel") init() { container.loadPersistentStores { description, error in if let error = error { print("Core Data failed to load: \(error.localizedDescription)") } } } }


Injecting the Context

The viewContext is an area in memory where you manipulate your Core Data objects before saving them to the database.

You must inject this context into the SwiftUI Environment so that all your views can access it.

Environment Injection:

import SwiftUI

@main struct MyApp: App { @StateObject private var dataController = DataController() var body: some Scene { WindowGroup { ContentView() // Injecting the context into the app's environment .environment(.managedObjectContext, dataController.container.viewContext) } } }


The @FetchRequest Property Wrapper

To display data from the database, SwiftUI provides the brilliant @FetchRequest property wrapper.

It automatically fetches data from Core Data and magically keeps your SwiftUI UI updated whenever the database changes!

Fetching and Displaying Data:

struct ContentView: View {
    // We assume an entity named "Student" was created in Xcode
    @FetchRequest(sortDescriptors: [SortDescriptor(\.name)]) var students: FetchedResults<Student>
    var body: some View {
        List(students) { student in
            Text(student.name ?? "Unknown")
        }
    }
}

Adding and Saving Data

To add data, you simply create a new instance of your Entity, passing in the Environment's managed object context.

Then, you call try context.save() to commit the changes to the hard drive permanently!


Exercise

Which SwiftUI property wrapper is used to automatically retrieve and monitor records from Core Data?