diff --git a/Source/DATAStack.swift b/Source/DATAStack.swift index ad2271e..0b0baa1 100644 --- a/Source/DATAStack.swift +++ b/Source/DATAStack.swift @@ -27,6 +27,8 @@ import CoreData private var containerURL = URL.directoryURL() + private let backgroundContextName = "DATAStack.backgroundContextName" + /** The context for the main queue. Please do not use this to mutate data, use `performInNewBackgroundContext` instead. @@ -232,6 +234,7 @@ import CoreData */ @objc public func newBackgroundContext() -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: DATAStack.backgroundConcurrencyType()) + context.name = backgroundContextName context.persistentStoreCoordinator = self.persistentStoreCoordinator context.undoManager = nil context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy @@ -373,6 +376,11 @@ import CoreData // Can't be private, has to be internal in order to be used as a selector. @objc func backgroundContextDidSave(_ notification: Notification) throws { + let context = notification.object as? NSManagedObjectContext + guard context?.name == backgroundContextName else { + return + } + if Thread.isMainThread && TestCheck.isTesting == false { throw NSError(info: "Background context saved in the main thread. Use context's `performBlock`", previousError: nil) } else {