Search code examples
iosswiftcore-datapersistence

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


Solution

  • 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)")
            }
        }
    }