The stack, contexts and threads
Core Data has three main pieces:
- The model: your entities, like
NotewithtitleandcreatedAt. - The persistent container: opens the database file and sets everything up.
- ContextsManaged object contextA Core Data scratchpad on its own queue, where objects are created, changed and saved.Open in glossary →: scratchpads where you create, change and delete objects, then save. Think of a context as a desk: you take objects out of the cabinet (the database), work on them on your desk, and
save()puts the changes back.
The rule that prevents most crashes: each context has its own queue, and its objects may only be used on that queue.
viewContextbelongs to the main queue. Use it for everything the UI shows.- Background contexts do heavy work, like importing 5,000 notes from the server, inside
perform { }, which runs the code on that context’s own queue.
To give an object to another context, pass its objectID, a stable identifier, and load the object again in the other context.
NSPersistentContainer wires the model, the persistent store coordinator and contexts. The viewContext is a main-queue context for UI reads and small edits; imports, sync and batch work go in newBackgroundContext() or performBackgroundTask, always inside perform/performAndWait (or await context.perform), because every NSManagedObjectContext is confined to its queue and NSManagedObjects aren’t Sendable. Cross-context references go through NSManagedObjectID (permanent after save; call obtainPermanentIDs if you hand off before saving). Set viewContext.automaticallyMergesChangesFromParent = true so background saves propagate, choose a merge policy (NSMergeByPropertyObjectTrumpMergePolicy is the common default: in-memory changes win per property), and model natural keys with unique constraints so inserting an existing id becomes an update instead of a duplicate. Run development builds with -com.apple.CoreData.ConcurrencyDebug 1, which traps on any cross-queue access, turning rare EXC_BAD_ACCESS crashes into immediate, debuggable ones. In SwiftUI, @FetchRequest observes the view context; in UIKit, NSFetchedResultsController drives diffable snapshots.
import CoreData
final class Persistence {
static let shared = Persistence()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "Notes")
if inMemory {
container.persistentStoreDescriptions.first?.url = URL(filePath: "/dev/null") // tests and previews
}
container.loadPersistentStores { _, error in
if let error { Logger.storage.fault("Store failed to load: \(error)") } // handled below, not fatalError
}
let view = container.viewContext
view.automaticallyMergesChangesFromParent = true // background saves show up in the UI
view.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
}
/// Imports server notes off the main thread. `serverID` has a unique constraint, so re-imports update.
func importNotes(_ dtos: [NoteDTO]) async throws {
let context = container.newBackgroundContext()
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
try await context.perform { // runs on the context's queue
for dto in dtos {
let note = Note(context: context)
note.serverID = dto.id
note.title = dto.title
note.updatedAt = dto.updatedAt
}
try context.save()
}
}
}
// SwiftUI: reads from the view context and updates when it changes
struct NotesList: View {
@FetchRequest(sortDescriptors: [SortDescriptor(\.updatedAt, order: .reverse)])
private var notes: FetchedResults<Note>
var body: some View {
List(notes) { note in Text(note.title ?? "Untitled") }
}
}viewContextis used by@FetchRequest, on the main queue, for the list.newBackgroundContext()+performdoes the import on a background queue, so scrolling stays smooth even with thousands of notes.automaticallyMergesChangesFromParentmakes the list update by itself when the background context saves.- The unique constraint on
serverID(set in the model editor, under the entity’s Constraints) plus the merge policy means importing the same note twice updates it instead of creating a duplicate.
Tap the line with the bug.
func importNotes(_ dtos: [NoteDTO]) {
DispatchQueue.global().async {
let context = Persistence.shared.container.viewContext
for dto in dtos {
let note = Note(context: context)
note.title = dto.title
}
try? context.save()
}
}Hint: Which queue does viewContext belong to, and which queue is this code on?
The viewContext belongs to the main queue, but this code uses it on a background queue, while the UI may be reading it at the same time. Most of the time nothing happens; occasionally the context’s internal state is corrupted, and the app crashes far away, with EXC_BAD_ACCESS or a strange Core Data exception. Running with -com.apple.CoreData.ConcurrencyDebug 1 makes it crash right here, every time.
Use a background context and do all the work inside its perform:
func importNotes(_ dtos: [NoteDTO]) {
Persistence.shared.container.performBackgroundTask { context in
for dto in dtos {
let note = Note(context: context)
note.title = dto.title
}
try? context.save()
}
}Predict the output
The background import saves 50 new notes. The view context's automaticallyMergesChangesFromParent is false (the default), and the list uses @FetchRequest on the view context. What does the list show right after the save?
Each context has its own snapshot. A save from a background context goes to the store, but the view context isn't told unless automaticallyMergesChangesFromParent is true (or you merge the NSManagedObjectContextDidSave notification yourself). With it on, @FetchRequest sees the merged changes and the list updates.
Practice: open a note on the main queue from a background result
A background search finds a matching note and should open it in the UI. You can’t pass the Note object to the main queue, but you can pass its objectID:
func findAndOpen(text: String) async throws {
let context = Persistence.shared.container.newBackgroundContext()
let id: NSManagedObjectID? = try await context.perform {
let request = Note.fetchRequest()
request.predicate = NSPredicate(format: "title CONTAINS[cd] %@", text)
request.fetchLimit = 1
return try context.fetch(request).first?.objectID // an ID, safe to pass around
}
guard let id else { return }
await MainActor.run {
let viewContext = Persistence.shared.container.viewContext
if let note = try? viewContext.existingObject(with: id) as? Note {
router.open(note) // the same note, from the main-queue context
}
}
}existingObject(with:) loads the object in the view context, or throws if it was deleted in the meantime.
Fetching efficiently
- Faults: fetched objects are placeholders until a property is read; reading a relationship in a loop fires one query per object (the N+1 problem). Use
relationshipKeyPathsForPrefetchingfor relationships you’ll touch. fetchBatchSize(e.g. 20) for long lists: Core Data loads rows in batches as you scroll;@FetchRequestandNSFetchedResultsControllerrespect it.propertiesToFetch/.dictionaryResultTypefor read-only aggregates, andNSExpressionfor counts and sums in SQL instead of in memory.- Indexes: add fetch indexes in the model for attributes you filter or sort on.
-com.apple.CoreData.SQLDebug 1prints the SQL and timings, the quickest way to spot unbounded fetches.
viewContext: main queue, UI. Background work:newBackgroundContext()/performBackgroundTask, always inperform(await context.perform).- Objects are confined to their context and not
Sendable: passNSManagedObjectID(permanent after save), reload withexistingObject(with:). automaticallyMergesChangesFromParent = true,NSMergeByPropertyObjectTrumpMergePolicy, unique constraints for upserts.-com.apple.CoreData.ConcurrencyDebug 1in development;SQLDebugfor queries.- Efficiency:
fetchBatchSize, prefetching relationships, fetch indexes, dictionary results andNSExpressionfor aggregates.
Check this part
Which context should the UI read from?
How do you hand a note found in a background context to the main queue?
What does -com.apple.CoreData.ConcurrencyDebug 1 do?
Re-importing a note with the same serverID should update it. What makes that happen?