Retrive object but done want to save coredata iOS swift

 Problem:

I'm having preview option for some data but if i save other data came from server the temp data also saved in my coredata. How to avoid that?


Solution:


    let context  =  NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)

    context.persistentStoreCoordinator = getContext().persistentStoreCoordinator


The above code solves my problem.


Below are coredata initilisations in my appdelegate.


//  MARK: -  Get the context

func getContext () -> NSManagedObjectContext {

    var context: NSManagedObjectContext?

    if #available(iOS 10.0, *) {

        context = persistentContainer.viewContext

    } else {

        context = managedObjectContext

    }

    

    return context!

}


    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: APP_INFO.containerName)

        let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: APP_INFO.appGroup)

        if let url = dir?.appendingPathComponent(APP_INFO.containerName) {

            let persistentStoreDescription = NSPersistentStoreDescription(url: url)

            

            // Configure Persistent Store Description

            persistentStoreDescription.type = NSSQLiteStoreType

            persistentStoreDescription.shouldMigrateStoreAutomatically = true

            persistentStoreDescription.shouldInferMappingModelAutomatically = true

            container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

            

            container.persistentStoreCoordinator.addPersistentStore(with: persistentStoreDescription, completionHandler: { (persistentStoreDescription, error) in

                if let error = error {

                    print("Container error : ", "Unable to Add Persistent Store")

                    print("Container localizedDescription : ", "\(error.localizedDescription)")

                }

            })

        }

        return container

    }()

    

    lazy var managedObjectContext: NSManagedObjectContext = {

        // 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 = self.persistentContainer.persistentStoreCoordinator

        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

        managedObjectContext.persistentStoreCoordinator = coordinator

        return managedObjectContext

    }()

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift