skip to content

Managed Object Contexts

Contexts are scratchpads: a main-queue view context, background contexts for heavy writes and child contexts for staged edits. Thread confinement and merge policies decide how concurrent saves end.

on this pageshow

explore

questions

6

In Core Data, which queues do viewContext and a newBackgroundContext() context run on, and how do perform(_:), performAndWait(_:) and the async perform differ?

level: middleimportance: must knowfreq 78%

answer

  1. two concurrency types
  2. main queue versus private queue
  3. enqueue and return, or block
  4. await the block's value

basics

~20 s

viewContext is a main-queue context for the UI; newBackgroundContext() returns a new private-queue context for imports. perform(:) queues a block and returns, performAndWait(:) blocks until it ends, and async perform suspends and returns its result.

solid answer

~40 s

`NSPersistentContainer` creates `viewContext` as a main-queue context bound to the app's main queue, so UI code on the main thread may use it directly. `newBackgroundContext()` returns a fresh private-queue context on every call, and `performBackgroundTask(_:)` runs a block on another new one. A private queue can only be reached through the context's own methods: `perform(_:)` enqueues the block and returns at once; `performAndWait(_:)` runs it on the context's queue but does not return until it finishes, and it is reentrant; the async `perform(schedule:_:)` from iOS 15 suspends the caller and returns the block's value or rethrows its error. For a 40,000-row statement import I would use a background context with `try await context.perform { ... }` and end the block with `save()`, never `performAndWait(_:)` from the main thread.

code

swift · 26 lines
swift
import CoreData

struct StatementRow: Sendable {
    let amount: Double
    let date: Date
}

func importStatement(_ rows: [StatementRow], into container: NSPersistentContainer) async throws {
    let context = container.newBackgroundContext()
    try await context.perform {
        for row in rows {
            let expense = NSEntityDescription.insertNewObject(forEntityName: "Expense", into: context)
            expense.setValue(row.amount, forKey: "amount")
            expense.setValue(row.date, forKey: "date")
        }
        if context.hasChanges {
            try context.save()
        }
    }
}

@MainActor
func monthlyCount(in container: NSPersistentContainer) throws -> Int {
    let request = NSFetchRequest<NSManagedObject>(entityName: "Expense")
    return try container.viewContext.count(for: request)
}

go deeper

for a junior

Recall that viewContext belongs to the main queue and is what screens read, and that heavy work such as an import goes to a background context instead.

for a middle

Explain the two concurrency types, that newBackgroundContext() and performBackgroundTask(:) create private-queue contexts, and how perform(:), performAndWait(_:) and the async perform schedule and return.

for a senior

Show the traps: performAndWait(_:) freezing the UI from the main thread, a trailing closure resolving to the async overload, and sibling contexts that do not see each other's saves without a merge.

for a principal

Frame this as the base of a team rule: which code may call viewContext directly, which work must go to a background context, and whether jobs share one writer context or each get their own.

## Two kinds of context A **managed object context** (`NSManagedObjectContext`) is Core Data's scratchpad: you fetch, insert, change and delete objects in it, and nothing reaches the store until you call `save()`. Every context is created with a **concurrency type** that ties it to one queue: - **Main queue** (`.mainQueue`, the Objective-C `NSMainQueueConcurrencyType`): the context uses the app's main queue and its event loop. Use it for objects that feed the user interface. - **Private queue** (`.privateQueue`, `NSPrivateQueueConcurrencyType`): the context creates its own serial queue when it is initialized. Apple's documentation says you can reach that queue only through `perform(_:)` and `performAndWait(_:)`. The third type, thread confinement, has been deprecated since iOS 9; `NSManagedObjectContext(.privateQueue)` and `init(concurrencyType:)` are the initializers to use. ## What the container hands you | API | Concurrency type | Lifetime | |---|---|---| | `viewContext` | main queue | one per container, created with it | | `newBackgroundContext()` | private queue | a new context on every call, yours to keep | | `performBackgroundTask(_:)` | private queue | a new context per call, passed to your block | Apple's documentation says `viewContext` and every `newBackgroundContext()` context are associated directly with the `NSPersistentStoreCoordinator`, so they are siblings, not parent and child. A background save reaches the store, but `viewContext`'s already loaded objects keep their old values unless `viewContext.automaticallyMergesChangesFromParent` is `true`, and it is off until you set it. ## Getting work onto the right queue 1. **`perform(_:)`** (iOS 5) enqueues the block on the context's queue and returns immediately. Its header says the block is wrapped in an autorelease pool and a call to `processPendingChanges()`. 2. **`performAndWait(_:)`** runs the block on the context's queue but does not return until it ends. It is **reentrant**: calling it again from inside the block is safe. Since iOS 15 a generic overload returns the block's value and rethrows its error. 3. **`perform(schedule:_:)`** (iOS 15, Swift overlay) is `async`: the caller suspends, the block runs on the context's queue, and its return value or error comes back through `await`. `schedule` defaults to `.immediate`; `.enqueued` is the other case. Apple's documentation names two exceptions to "always go through perform": setter methods on a queue-based context are thread-safe, and code already running on the main thread may call a main-queue context such as `viewContext` directly. ## A background import in practice Treat each block as one unit of work. As soon as it ends, other blocks may run on the same context, so do the whole batch inside it and finish with `save()`, checking `hasChanges` first as the `save()` documentation advises. The first code example imports statement rows on a context from `newBackgroundContext()` and lets the dashboard count rows on `viewContext` from the main actor. The rows are a `Sendable` struct, because every block passed to `perform` is `@Sendable`. ## Traps worth naming - **The overload you did not mean.** Inside an `async` function, a trailing closure on `context.perform { }` resolves to the async overload, so the compiler requires `await`, plus `try` when the block throws. - **Blocking the main thread.** `performAndWait(_:)` called from the main thread on a private context makes the UI wait for the whole block: an import moved to a background context but called this way still freezes the dashboard. - **Plain dispatch queues.** `DispatchQueue.global().async { context.save() }` does not run on a private context's queue; only that context's perform methods do. - **Siblings do not share objects.** Saving a background context does not change objects already loaded in `viewContext` until a merge happens, which is why the merge setting matters as soon as a second context writes. Background contexts keep heavy work off the main queue, `viewContext` stays the one the UI reads, and the perform family is the only door into a private queue.

  • Is it ever fine to call viewContext without perform(_:)?
    Yes. Apple's documentation says code running on the main thread may call a main-queue context directly, because that context is bound to the main queue. From any other thread or task you still wrap the work in `viewContext.perform`. Setter methods on queue-based contexts are documented as thread-safe from any thread, but fetching, saving and touching objects are not.
  • Why might performBackgroundTask(_:) be a poor fit for a long import pipeline?
    Each call creates a new private-queue context, so two calls can run at the same time and their saves can collide on the same rows. A single context from `newBackgroundContext()` that you keep runs its blocks one after another on its own queue, which serialises the import's writes.
  • What does performAndWait(_:) being reentrant mean?
    A block running inside `performAndWait(_:)` may call `performAndWait(_:)` again on the same context without deadlocking; the documentation states that this is safe. It does not make a blocking call from the main thread cheap: the caller still waits for every nested block.

  • Saying viewContext runs on a background queue so the UI never waits for it.
  • Wrapping context work in DispatchQueue.global().async instead of the context's perform methods.
  • Thinking newBackgroundContext() returns the same shared context every time.
  • Calling performAndWait(_:) from the main thread for a long import and calling it background work.
  • Believing a background save instantly updates objects already loaded in viewContext.
open as a page

Your Core Data expense app crashes now and then after a background import passes fetched Expense objects to the dashboard; why, and how do you catch and fix it?

level: seniorimportance: must knowfreq 66%

basics

~20 s

Managed objects are bound to their context's queue, so reading private-queue Expense objects on the main thread is a data race that crashes or corrupts data at random. Run with -com.apple.CoreData.ConcurrencyDebug 1 to trap it, and pass NSManagedObjectIDs instead.

open as a page

In Core Data, how does a child context make an expense edit sheet cancellable, and what does saving that child context actually write?

level: middleimportance: should knowfreq 55%

basics

~20 s

Give the sheet a context whose parent is viewContext and load the expense into it by objectID. Cancel just discards that child. Saving the child only pushes its changes into viewContext; nothing reaches the store until viewContext saves too.

open as a page

In Core Data, after an NSBatchDeleteRequest removes old expenses, why does the dashboard still show them, and how do you make viewContext see the change?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Batch requests change rows in the store without loading objects or saving a context, so viewContext gets nothing to merge. Set resultType to return object IDs and pass them to NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:), or consume persistent history.

open as a page

In Core Data, why does a viewContext save fail with error 133020 after a background import changed the same Expense, and which merge policy fits?

level: seniorimportance: should knowfreq 50%

basics

~10 s

133020 is NSManagedObjectMergeError: viewContext edited an Expense whose stored row changed after it was loaded, and the default NSErrorMergePolicy refuses such saves. Setting NSMergePolicy.mergeByPropertyObjectTrump keeps the user's edited properties and the import's other changes.

open as a page

As the lead on a Core Data expense app, what context rule would you set for which contexts write, which read, and how changes reach the UI?

level: principalimportance: should knowfreq 35%

basics

~20 s

A common rule: viewContext serves reads and small edits, one kept background context does imports, every write path ends in a merge viewContext receives, each context gets a merge policy, and debug builds run the concurrency argument.

open as a page