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?
answer
- objects belong to one queue
- intermittent, not deterministic
- a launch argument that asserts
- hand over an identifier instead
basics
~20 sManaged 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.
solid answer
~40 sCore Data protects contexts and their objects by queue confinement: an object fetched in the import's private-queue context may only be touched on that queue. Reading its properties on the main thread can fire a fault or race the import's next block, which is why the crash is intermittent and why Apple warns of data corruption. To make it deterministic I add `-com.apple.CoreData.ConcurrencyDebug 1` to the scheme's launch arguments: Core Data logs that multithreading assertions are enabled and stops at the first wrong-queue access. The fix is to return `objectID`s from the import's `perform` block and rebuild the objects in `viewContext` with `existingObject(with:)`, after the import has saved, since unsaved objects only have temporary IDs.
code
bash · 1 line-com.apple.CoreData.ConcurrencyDebug 1go deeper
Recall the rule: an object fetched from a context stays on that context's queue, and you pass its objectID, not the object, to other code.
Explain why cross-queue reads crash only sometimes, and how object(with:) and existingObject(with:) turn an ID back into an object in another context.
Diagnose from the symptoms, enable the concurrency debug launch argument to make it deterministic, and fix the hand-off including the temporary-ID case.
Turn it into team policy: no managed objects in cross-queue signatures, the debug argument on in every debug scheme and UI test run, and review checks for perform blocks.
## The rule being broken Core Data is not thread-safe object by object. Apple's background guide gives two rules: bind each **managed object context** to the queue it was created for, and bind every **managed object** fetched from it to that same queue. An `Expense` fetched inside the import's `perform` block belongs to the import context's private queue. Handing that array to the dashboard and reading `amount` on the main thread breaks the rule. The documentation's warning is blunt: passing managed object instances between queues "can result in corruption of the data and termination of the app." ## Why the crash is intermittent Nothing checks the rule at run time by default. Whether the illegal read crashes depends on timing: - the property may still be a **fault**, so reading it makes Core Data fulfil the fault through the context, from the wrong queue; - the import context may be running its next block, changing or refreshing that object at the same moment; - or the read may happen to land between blocks and appear to work. So the app passes testing, then crashes in the field with stack traces deep inside Core Data that point nowhere near the bad line. The header types reflect the rule: `NSManagedObject` is declared non-Sendable, while `NSManagedObjectContext` and `NSManagedObjectID` are Sendable. Swift 6 language mode does not catch every such hand-off, though: returning a freshly fetched `[NSManagedObject]` from `await context.perform` and reading it on the main actor can compile without a diagnostic, so the runtime check below still matters. ## Catching it: the concurrency debug argument Add the launch argument in the scheme (Product > Scheme > Edit Scheme > Run > Arguments Passed On Launch): ```bash -com.apple.CoreData.ConcurrencyDebug 1 ``` With it, Core Data turns on its multithreading assertions. The console logs that they are enabled, and the first access to a context or managed object off its queue stops the app at that line instead of somewhere later. Keep it on in the debug scheme and in UI test runs so violations fail fast. ## Fixing it: pass identifiers, not objects `NSManagedObjectID` is the documented way to hand a reference between queues: a compact identifier that names the same object in every context of the stack. 1. Inside the import context's `perform` block, finish the work and call `save()`. 2. Return `objects.map(\.objectID)` from the block, not the objects. 3. On the main actor, turn each ID into a `viewContext` object. | Method | Returns | When the row is missing | |---|---|---| | `object(with:)` | the registered object or a fault, never `nil`, no I/O | the fault throws an exception later, when fired | | `existingObject(with:)` | a fully loaded object, never a fault | throws an error at the call | | `registeredObject(for:)` | only an object already in the context | returns `nil`, never does I/O | `existingObject(with:)` is the safer choice when the row might have been deleted meanwhile; `object(with:)` is cheaper when you know it exists. ## The temporary ID trap A newly inserted object has a **temporary** ID (`isTemporaryID` is true) until it is saved to a store. Another context cannot load a row that is not in the store yet, so hand over IDs only after the import saves, or call `obtainPermanentIDs(for:)` first. ## Checklist for review - No function that crosses queues or actors takes or returns `NSManagedObject`; it takes `NSManagedObjectID` or plain values. - Every use of a private context sits inside `perform` or `performAndWait`. - `viewContext` objects are used only on the main thread or inside `viewContext.perform`. - The debug scheme runs with the concurrency argument. The same idea appears in SwiftData, which hands models between actors by a persistent identifier; that version belongs to the SwiftData material, and the Swift rules for Sendable belong to the Swift concurrency lessons.
- Can you pass the background context itself to the main thread instead?You can pass the reference, since the context type is Sendable, but the main thread still has to use it through `perform` or `performAndWait`, and its objects stay on its private queue. Passing the context does not let the UI read its objects directly; the dashboard should read `viewContext` objects.
- Why might the crash vanish when you add logging or breakpoints?The bug is a race: whether the main thread's read collides with the import's work depends on timing. Logging and breakpoints change the timing, so the symptom moves. The debug launch argument makes Core Data check the queue on every access, which turns a timing-dependent crash into a deterministic stop.
- What happens if you call object(with:) for an ID whose row an import has already deleted?`object(with:)` assumes the object exists and returns a fault without checking. When the code later reads a property, the fault cannot be fulfilled and Core Data throws an exception. `existingObject(with:)` checks at the call and throws a catchable error instead.
- Reading managed object attributes on any thread is safe as long as nothing writes.
- The crash is a Core Data bug because it does not happen every time.
- Swift 6 language mode already catches every managed object that crosses queues.
- Wrapping the main-thread read in a lock makes cross-queue access safe.
- A temporary objectID can be passed to viewContext before the import saves.