skip to content

Persistent Stack Setup

NSPersistentContainer wires model, coordinator and store together over SQLite, memory or a binary file. Interviewers ask you to sketch the stack, and an in-memory store is the expected test answer.

on this pageshow

explore

questions

5

In Core Data, what does NSPersistentContainer build for you, and what must happen before its viewContext can save?

level: juniorimportance: must knowfreq 75%

answer

  1. model, coordinator and context in one object
  2. the name finds the compiled model
  3. change descriptions before loading
  4. one completion call per store
  5. no loaded store, save raises an exception

basics

~10 s

NSPersistentContainer loads the managed object model it is named after, builds the persistent store coordinator and a main-queue viewContext. Nothing persists until loadPersistentStores(completionHandler:) has added each store description and reported every store's error.

solid answer

~40 s

`NSPersistentContainer(name: "FieldSales")` looks up the compiled `FieldSales` model in the main bundle, builds an `NSPersistentStoreCoordinator` over it and exposes `viewContext`, a context tied to the main queue. Its `persistentStoreDescriptions` start with one SQLite description for `FieldSales.sqlite` in `defaultDirectoryURL()`. Any change to a description (its URL, type or options) has to be made before `loadPersistentStores(completionHandler:)`, which adds the stores and calls its completion once per description on the calling thread; by default the store is added synchronously, so the completion has run before the call returns. Check the error there: if a store failed and the app carries on, the first `save()` raises an exception because the coordinator has no persistent stores.

code

swift · 17 lines
swift
import CoreData

final class Persistence {
    let container: NSPersistentContainer

    init() {
        // Looks up FieldSales.momd in the main bundle and names the store FieldSales.sqlite.
        container = NSPersistentContainer(name: "FieldSales")
        // Change persistentStoreDescriptions here, before loading.
        container.loadPersistentStores { description, error in
            // Called once per store description, on the calling thread.
            if let error {
                fatalError("Could not load \(description.url?.lastPathComponent ?? "store"): \(error)")
            }
        }
    }
}

go deeper

for a junior

Recall the three pieces the container builds (model, coordinator, viewContext), that the name finds the model and names the store, and that nothing works until loadPersistentStores has run.

for a middle

Explain the default description, why descriptions must be set before loading, and that the completion fires once per store on the calling thread, synchronously unless shouldAddStoreAsynchronously is set.

for a senior

Show what happens when a load error is ignored: the no-persistent-stores exception on the first save that do-catch cannot catch. Describe how a shipping app logs and contains a failed load.

for a principal

Frame the stack as one shared object per store file with a checked load, and decide who owns the policy for a failed load so screens never save into a half-built stack.

## What the container assembles Apple's documentation calls the group of objects that load, track and save your data the **Core Data stack**. `NSPersistentContainer` (iOS 10) builds it in one step and keeps a reference to each piece: - **`managedObjectModel`**: the `NSManagedObjectModel`, the compiled description of your entities and attributes. - **`persistentStoreCoordinator`**: the `NSPersistentStoreCoordinator` that saves and fetches objects from the stores. It presents all of its stores to a context as one aggregate and does its work serially on a private queue. - **`viewContext`**: an `NSManagedObjectContext` created automatically and associated with the main queue, connected directly to the coordinator. It is the context the UI reads from. - **`persistentStoreDescriptions`**: an array of `NSPersistentStoreDescription` objects, one per store the container will load. A new container holds one description: the SQLite store type, a URL of `<name>.sqlite` inside `defaultDirectoryURL()`, and no configuration name. Apple's setup guide creates this container once and shares it, usually as a singleton or an injected dependency, because every context the app makes later comes from this one coordinator. ## The name does two jobs The string you pass to `init(name:)` is not a label. The container uses it to **find the model** (a compiled `FieldSales.momd` in the main bundle) and to **name the store file** (`FieldSales.sqlite`). If no model with that name exists, the console prints `CoreData: error: Failed to load model named FieldSales` and the container holds a model with no entities. When the model lives somewhere else, such as a framework, a test bundle or a model built in code, use `init(name:managedObjectModel:)`: the model you pass replaces the lookup, and the name still names the store. ## Loading the stores Creating a container opens nothing. The order is: 1. Create the container with its name (and model, if you pass one). 2. Adjust `persistentStoreDescriptions`: a different URL, an in-memory type, extra options. Apple's documentation is explicit that custom descriptions must be set before loading. 3. Call `loadPersistentStores(completionHandler:)`. 4. Inspect the `(NSPersistentStoreDescription, Error?)` pair the completion receives, once for **each** description. 5. Only then read and save through `viewContext`. The completion runs on the calling thread. `shouldAddStoreAsynchronously` defaults to `false`, so each store is added synchronously and the completion has already run when `loadPersistentStores` returns; set it to `true` and the store is added on a background queue instead. Calling `loadPersistentStores` again only loads descriptions that have not already been added successfully. ## When a store fails to load | Situation | What Core Data does | |---|---| | The model name matches nothing in the bundle | Logs `Failed to load model named …`; the model has no entities | | A store fails to load and the app ignores the error | The load completion receives the `NSError`; the coordinator stays without that store | | The app then calls `viewContext.save()` with no stores loaded | Raises `NSInternalInconsistencyException`: "This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation." | | The app fetches with no stores loaded | No error; the fetch returns only the unsaved objects the context holds | The save case is the dangerous one: it is an Objective-C exception, not a Swift error, so a `do`/`catch` around `save()` does not catch it and the app terminates. Apple's sample code calls `fatalError` in the completion during development, which at least fails at the cause. In a shipping app: - Log the error's `code` and `userInfo`; the user info names the file path and, for SQLite failures, the SQLite error code. - Stop the UI from saving into a container whose stores did not all load. - Treat a failed migration separately: the automatic migration options on the default description, what they infer, and how to recover when a migration fails are covered in the lesson on migrations. ## Where the rest of the stack goes The container also hands out background contexts with `newBackgroundContext()` and `performBackgroundTask(_:)`; which context does which work, and how saves reach the UI, is the lesson on managed object contexts. What belongs to this setup step is the model lookup, the descriptions and a checked load. A short review checklist for stack code: - One container per store file in the process, created once and shared, not one per screen. - The name matches the compiled model, or the model is passed in explicitly. - Every description change happens before `loadPersistentStores(completionHandler:)`. - The completion inspects the error for each store instead of ignoring the second argument. - Nothing touches `viewContext` before the load has finished.

  • When would you use init(name:managedObjectModel:) instead of init(name:)?
    When the model isn't a compiled model of that name in the main bundle: it lives in a framework, a Swift package or a test bundle, or you build it in code. It's also how tests share one loaded model across many containers. The name you pass still names the store file.
  • The console prints 'Failed to load model named FieldSales'. What is wrong?
    The container found no compiled model called FieldSales in the main bundle: the .xcdatamodeld has another name, isn't a member of the target, or sits in another bundle. The container then has a model with no entities. Fix the name or load the model yourself and pass it in.
  • Does calling loadPersistentStores(completionHandler:) a second time load the stores again?
    No. It loads only the descriptions that have not already been added successfully, so a second call retries a store that failed or adds a description you appended since. Stores that already loaded are left alone.

  • Creating the NSPersistentContainer opens the store file straight away.
  • The load completion runs once, after every store has finished loading.
  • Store descriptions can be changed after loading and apply on the next save.
  • A store that failed to load shows up as a Swift error thrown by save().
  • The container's name is only a debugging label.
open as a page

In Core Data unit tests, how do you build a fresh stack for every test, and when is NSInMemoryStoreType the wrong store type?

level: middleimportance: must knowfreq 60%

basics

~10 s

Create a new NSPersistentContainer per test from one shared model, with an NSInMemoryStoreType description or a SQLite store at /dev/null. The in-memory type cannot run SQLite-only work such as batch requests; /dev/null SQLite can.

open as a page

In Core Data, how do you move an app's SQLite store into an app group so its widget extension can open the same file?

level: middleimportance: should knowfreq 40%

basics

~20 s

Give the app and widget the same App Group, open the store at a URL inside its container, and move existing users' store there once with the coordinator's replacePersistentStore and destroyPersistentStore, never a FileManager copy of the .sqlite file alone.

open as a page

Your Core Data app shares its store with a widget; why does the app's list miss changes the widget saved, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The widget saves through its own coordinator in another process, so no save notification reaches the app's contexts. Turn on persistent history and remote change notifications in both processes, then on each remote change fetch history after your saved token and merge it.

open as a page

In Core Data, how do you ship a read-only product catalogue store beside the user's own store in one NSPersistentContainer?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Split the entities into two model configurations, give the container one NSPersistentStoreDescription per store with its configuration name, and mark the bundled catalogue's description isReadOnly. Core Data routes each fetch and save to the store whose configuration holds the entity.

open as a page