Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix attempt to recursively call -save error with coredata?

I am getting this error randomly while saving in core data

Unresolved error Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo={message=attempt to recursively call -save: on the context aborted, stack trace=(

Everything is working fine for last 3 month but recently I due to change in app I have to call a lot of fetch and save request and some of them are in loop and some in closure after making these changes I faced this error.

Here is code for coredata manager

import Foundation
import CoreData
class CoreDataStack {
    private init() {

    }

    class func getContext () -> NSManagedObjectContext {
        return CoreDataStack.managedObjectContext
    }
    // MARK: - Core Data stack

    static var managedObjectContext: NSManagedObjectContext = {

        var applicationDocumentsDirectory: URL = {
            // The directory the application uses to store the Core Data store file. This code uses a directory named "com.cadiridris.coreDataTemplate" in the application's documents Application Support directory.
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return urls[urls.count-1]
        }()

        var managedObjectModel: NSManagedObjectModel = {
            // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
            let modelURL = Bundle.main.url(forResource: "Thyssenkrupp", withExtension: "momd")!
            return NSManagedObjectModel(contentsOf: modelURL)!
        }()

        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
            let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
            let url = applicationDocumentsDirectory.appendingPathComponent("Thyssenkrupp.sqlite")
            var failureReason = "There was an error creating or loading the application's saved data."
            let options = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption:true ]
            do {
                try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
            } catch {
                // Report any error we got.
                var dict = [String: AnyObject]()
                dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
                dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

                dict[NSUnderlyingErrorKey] = error as NSError
                let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
                // Replace this with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
                //abort()
            }

            return coordinator
        }()

        // 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.
        let coordinator = persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

    // MARK: - Core Data Saving support

    class func saveContext () {
        DispatchQueue.main.async { 
            if managedObjectContext.hasChanges {
                do {
                    try managedObjectContext.save()
                } catch {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    let nserror = error as NSError
                    print("Unresolved error \(nserror), \(nserror.userInfo)")
                    //abort()
                }
            }
        }

    }
}

Please provide any suggestion why this error coming

like image 610
Varun Naharia Avatar asked Nov 07 '22 19:11

Varun Naharia


1 Answers

The problem was saving data to CoreData to frequently, Yes you can CoreData as Frequently as you want but it will through this error on console if you add/delete/update a data and save it in a loop doing this way will cause this error, not always but it's better to save CoreData after loop is complete. As Saving to Core Data is important in case where we perform Create,Update, Delete operation and we didn't save the CoreData app crashes/closed down for some reason then data will be lost from the point we last save the CoreData. Saving to CoreData is like a checkpoint everything is saved. So saving in a loop is not efficient way to do.

like image 134
Varun Naharia Avatar answered Nov 14 '22 21:11

Varun Naharia