0Pricing
Swift Academy · Lesson

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, NSFetchRequest

Creating 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

  1. Core Data Stack: NSPersistentContainer Setup
  2. SwiftData @Model and ModelContext
  3. Relationships and Fetch Descriptors
  4. Lightweight Migrations and CloudKit Sync
← Back to Swift Academy