0Pricing
Swift Academy · Lesson

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 — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit 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)") }
}

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.

Frequently asked questions

Is the “Core Data Stack: NSPersistentContainer Setup” lesson free?

Yes — the full text of “Core Data Stack: NSPersistentContainer Setup” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

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

  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