You wrote " When using a single managed object context in Core Data, everything runs on the main UI thread. However, this project has a separate private queue context which acts as the root context, letting you save data on a background thread. The main context exposed by the Core Data stack is a child of this context." Great.
But why did made opposite steps in code provided to me???
import Foundation
import CoreData
open class CoreDataStack {
let modelName: String
public init(modelName: String) {
self.modelName = modelName
}
public lazy var mainContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
public lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores { (storeDescription, error) in
if let error = error as? NSError {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
public func newDerivedContext() -> NSManagedObjectContext {
let context = storeContainer.newBackgroundContext()
return context
}
public func saveContext() {
saveContext(mainContext)
}
public func saveContext(_ context: NSManagedObjectContext) {
if context != mainContext {
saveDerivedContext(context)
return
}
context.perform {
do {
try context.save()
} catch let nserror as NSError {
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
public func saveDerivedContext(_ context: NSManagedObjectContext) {
context.perform {
do {
try context.save()
} catch let nserror as NSError {
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
self.saveContext(self.mainContext)
}
}
}
Here. you performed save action like it is mainContext is parent and backgroundContext is a child. Why??? Please answer. do not ignore this question. Thank you.
public func saveDerivedContext( context: NSManagedObjectContext) {_
_ context.perform {_
_ do {_
_ try context.save()_
_ } catch let nserror as NSError {_
_ fatalError(“Unresolved error (nserror), (nserror.userInfo)”)_
_ }_
_ self.saveContext(self.mainContext)_
_ }_
_ }_
}