As asked
Your app uses Core Data with a view context on the main thread and a private context for background imports. You pass an NSManagedObject from the background context to a completion handler that runs on the main thread and update the UI with it. What goes wrong?
Sample answer outline
NSManagedObjects are bound to their context and must only be accessed on that context's queue. Passing the object across contexts is a data race: the background context may be deallocated or the fault may fire on the wrong thread, producing a crash or silent corruption. The correct fix is to pass the objectID (an NSManagedObjectID, which is thread-safe) and re-fetch the object on the destination context using object(with:). A strong answer also mentions that the view context should have automaticallyMergesChangesFromParent = true so changes from the private context propagate.
Expect these follow-ups
- What is NSManagedObjectContext.perform versus performAndWait and when does each matter?
- How do you batch-insert a million records into Core Data without blowing out memory?