Core Data Stack: NSPersistentContainer Setup
Setting up the persistent container, context and coordinator in a SwiftUI app.
Core Data Stack: NSPersistentContainer Setup is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
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)") }
}The Persistence Controller Pattern
Wrap the container in a singleton (or injectable) PersistenceController struct for clean access across the app.
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentContainer
init() {
container = NSPersistentContainer(name: "MyModel")
container.loadPersistentStores { _, error in
if let error { fatalError("\(error)") }
}
}
}viewContext and backgroundContext
viewContext is the main-thread context for UI. Use newBackgroundContext() for heavy operations.
let viewCtx = PersistenceController.shared.container.viewContext
let bgCtx = PersistenceController.shared.container.newBackgroundContext()Creating Managed Objects
Insert new objects using NSEntityDescription.insertNewObject or the generated class initializer.
let item = Item(context: viewCtx)
item.timestamp = Date()
try? viewCtx.save()Fetching Objects
Use NSFetchRequest to query Core Data objects with predicates and sort descriptors.
let request: NSFetchRequest<Item> = Item.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
let items = try? viewCtx.fetch(request)Saving the Context
Always call context.save() to persist changes. Wrap in do-catch for production code.
do {
try viewCtx.save()
} catch {
print("Save failed: \(error)")
viewCtx.rollback()
}SwiftUI Integration with @FetchRequest
Use @FetchRequest in SwiftUI views to automatically update the UI when Core Data changes.
struct ItemList: View {
@FetchRequest(
sortDescriptors: [SortDescriptor(\Item.timestamp, order: .reverse)]
) var items: FetchedResults<Item>
var body: some View {
List(items) { Text($0.timestamp!.formatted()) }
}
}Injecting viewContext into SwiftUI
Pass viewContext via the SwiftUI environment so views can read and write Core Data.
@main
struct MyApp: App {
let persistence = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistence.container.viewContext)
}
}
}Deleting Objects
Call context.delete(object) and then save to permanently remove an object.
viewCtx.delete(item)
try? viewCtx.save()In-Memory Store for Testing
Use an in-memory store to avoid touching the disk during unit tests.
let desc = NSPersistentStoreDescription()
desc.type = NSInMemoryStoreType
container.persistentStoreDescriptions = [desc]
container.loadPersistentStores { _, _ in }Quick Check
Which NSPersistentContainer context should be used for UI-driven Core Data reads and writes?
Lesson Recap
Set up Core Data with NSPersistentContainer, load stores, and wrap in a PersistenceController. Use viewContext on the main thread and newBackgroundContext() for heavy work. Integrate with SwiftUI via @FetchRequest and the managed object context environment key.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “Core Data Stack: NSPersistentContainer Setup” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “Core Data Stack: NSPersistentContainer Setup”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
What will I learn in “Core Data Stack: NSPersistentContainer Setup”?
Setting up the persistent container, context and coordinator in a SwiftUI app. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
How long does the “Core Data Stack: NSPersistentContainer Setup” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Core Data Stack: NSPersistentContainer Setup
- SwiftData @Model and ModelContext
- Relationships and Fetch Descriptors
- Lightweight Migrations and CloudKit Sync