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
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)")
}
}
}
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With