Core Data Stack: NSPersistentContainer Setup
Setting up the persistent container, context and coordinator in a SwiftUI app.
Core Data Overview
Core Data is Apple's object graph and persistence framework. It manages SQLite (or other stores) with an object-oriented API.
import CoreData
// Key classes: NSPersistentContainer, NSManagedObjectContext
// NSManagedObject, NSFetchRequestCreating NSPersistentContainer
Initialize NSPersistentContainer with your .xcdatamodeld model name and load persistent stores.
let container = NSPersistentContainer(name: "MyModel")
container.loadPersistentStores { desc, error in
if let error { fatalError("Core Data failed: \(error)") }
}All lessons in this course
- Core Data Stack: NSPersistentContainer Setup
- SwiftData @Model and ModelContext
- Relationships and Fetch Descriptors
- Lightweight Migrations and CloudKit Sync