Joe
Joe

Reputation: 879

viewContext is not getting saved in the database (app.sqlite)

I created a app to save the details of a student, using NSPersistanceContainer and while I'm getting the data from JSON and saving to db, at that time I'm getting fetch results count > 0. If I restarted the app the fetch result count returns 0.

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "Students_dev")

    let storeURL = try! FileManager
        .default
        .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("Students_dev.sqlite")
    print("URL :",storeURL)

    let storeDescription = NSPersistentStoreDescription(url: storeURL)
    storeDescription.shouldMigrateStoreAutomatically = true
    storeDescription.shouldMigrateStoreAutomatically = true
    container.viewContext.automaticallyMergesChangesFromParent = true
    container.persistentStoreDescriptions = [storeDescription]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext (context: NSManagedObjectContext) {
   
   persistentContainer.performBackgroundTask({ (context) in
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    })
}

The context is not empty while I'm saving to db, when I check the sqlite file the table is empty. Didn't get what's is missing from my side.

No data is being get inserted into SQL file screenshot of sql log

Upvotes: 9

Views: 6749

Answers (2)

Joe
Joe

Reputation: 879

The issue was on saveContext function, the context is not getting saved into the core-data "persistentContainer.performBackgroundTask", when i removed it it works fine.

Code

func saveContext (context: NSManagedObjectContext) {

    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

Upvotes: 5

kharrison
kharrison

Reputation: 3432

I think the cause of the CoreData warning is with this line of code:

container.viewContext.automaticallyMergesChangesFromParent = true

You are accessing the viewContext before the store is loaded. Try moving that line inside the load persistent store completion block:

container.loadPersistentStores(completionHandler: { (storeDescription, error) in
    if let error = error as NSError? {
        fatalError("Unresolved error \(error), \(error.userInfo)")
    }
    container.viewContext.automaticallyMergesChangesFromParent = true
})

Upvotes: 17

Related Questions