'This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation.'

376 views Asked by At

I am getting a crash at "try save()" this line.

extension NSManagedObjectContext {

/// Only save if `hasChanges`
func saveIfNeeded() throws {
    guard hasChanges else {
        return
    }

    do {
        try save()
    } catch {
        assertionFailure("Failed to save main context: \(error)")
        throw error
    }
}

/// Calls `saveIfNeeded` and then calls `saveIfNeededUpToRootContext()` on the `parentContext`.
func saveIfNeededUpToRootContext() throws {
    try saveIfNeeded()
    try parent?.saveIfNeededUpToRootContext()
}

}

In the appdelegte , appDidFinishLaunching : I have written :

defer {
            do {
                try DataStore.mainContext.saveIfNeededUpToRootContext()
            } catch {
                log("Failed to save \"App Feedback\" to Core Data: \(error)")
            }
        }

Basically calling the above method : saveIfNeededUpToRootContext.

Below is the initialisation of DataStore:

fileprivate let coordinator: NSPersistentStoreCoordinator
let mainContext: NSManagedObjectContext
var isLoaded = false

init() {
    guard let model = NSManagedObjectModel.mergedModel(from: nil) else {
        fatalError("No models in main bundle")
    }

    coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
    coordinator.name = "main_coordinator"

    mainContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    mainContext.name = "main_context"
    mainContext.persistentStoreCoordinator = coordinator
    mainContext.undoManager = nil

    let center = NotificationCenter.default
    center.addObserver(self, selector: #selector(save), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
    center.addObserver(self, selector: #selector(save), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
0

There are 0 answers