In my closure of my network request, I am inserting objects into core data using a private concurrency queue and getting a crash when I call "perform" on the private context.
Crash message in console:
libc++abi.dylib: terminating with uncaught exception of type NSException
The code that's causing the crash:
API.sync(onlyMe, syncToken: syncToken) { success, syncResponse in CoreDataUtils.privateContext.perform { // crashes on this line .... } } My Core Data stack (unfortunately located in the AppDelegate at the moment and not in a CoreDataStack class):
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) } catch { print(error) } return coordinator }() lazy var privateManagedObjectContext: NSManagedObjectContext = { // Initialize Managed Object Context var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) // Configure Managed Object Context managedObjectContext.parent = self.managedObjectContext return managedObjectContext }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator managedObjectContext.mergePolicy = NSRollbackMergePolicy //This policy discards in-memory state changes for objects in conflict. The persistent store’s version of the objects’ state is used return managedObjectContext }() Where CoreDataUtils.privateContext is:
class CoreDataUtils: NSObject { static let appDel = UIApplication.shared.delegate as! AppDelegate static let context: NSManagedObjectContext { return appDel.managedObjectContext } static let privateContext: NSManagedObjectContext { appDel.privateManagedObjectContext } } 