I was getting this crash intermittently as others have described, and I believe it was triggered by using a background context on the main thread. I have a class that wraps all CoreData interactions, and it uses NSPersistentContainer to accomplish this. I was using NSPersistentContainer.viewContext for everything which was causing intermittent issues when I accessed it from a background thread. I then added a member called backgroundContext that is initialized using NSPersistentContainer.newBackgroundContext(), and using that for everything is when I ran into the issue that we're all here for. So I added a computed value that uses the appropriate context based on the current thread:
private var context: NSManagedObjectContext { Thread.isMainThread ? container.viewContext : backgroundContext }
and I use that whenever I need an NSManagedObjectContext.
I have not been able to reproduce any CoreData crashes since I made this change. I hope this is helpful to somebody. I'll put the relevant part of my class below for reference.
final class CoreDataManager {
// MARK: Singleton
static let shared = CoreDataManager()
private init() { backgroundContext = container.newBackgroundContext() }
// MARK: Constants
private let container: PersistentContainer = {
let container = PersistentContainer(name: "LocalModel")
container.loadPersistentStores { description, error in
if let error = error {
CriticalError.handle(with: "Unable to load persistent stores: \(error)")
}
}
return container
}()
private let backgroundContext: NSManagedObjectContext
// MARK: Computed Values
private var context: NSManagedObjectContext { Thread.isMainThread ? container.viewContext : backgroundContext }
}