iOS Core Data: is enough saving only a background context? why or why not?

Viewed 1191

I would like to know if just saving a background context like in the below example is enough or I should also save the main context and why.

extension NSManagedObjectContext {
    

    private func saveOrRollback(context: NSManagedObjectContext) -> Bool {
        do {
            if context.hasChanges {
                try context.save()
                return true
            }
        } catch {
            log(error, message: "Couldn't save. Rolling back.", tag: .coreData)
            context.rollback()
            return false
        }
        return false
    }

    func performChanges(block: @escaping () -> Void) {
        let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        privateContext.parent = self
        privateContext.perform {
            block()
            _ = self.saveOrRollback(context: privateContext)
        }
    }
}
2 Answers

If you wanna save data on disk, you should also save it on main context.

Because if CoreData context have parent context, then save data just move changes to parent context.

Alternative: I recommended use new API. You can init CoreData via: NSPersistentContainer. It's more easy to use.

It's create separated content for UI:

persistentContainer.viewContext

It's can automatically merge changes to viewcontext.

persistentContainer.viewContext.automaticallyMergesChangesFromParent = true

And perform actions on background queue via much easy:

persistentContainer.performBackgroundTask { context in

    ...
            
    do {
        try context.save()
    }
    catch {
        print(error.localizedDescription)
    }
            
    ...
}

I would like to know if just saving a background context like in the below example is enough or I should also save the main context and why.

A Core Data managed object context is a workspace; changes that you make to the data exist only in that context until you save, at which point the changed objects are written back to the data store. If you made changes in the "background" context that you want to persist, you need to save that context. If you made changes in the "main" context that you want to persist, you need to save that context.

If there's a parent/child relationship between the two contexts, if you want to permanently save changes in the child context you'll need to first save in the child context and then save in the parent context. For example, if your "main" context is the parent store for your "background" context, saving in the background context will push the changes up to the main context, and you'll then need to save in the main context. (And if the main context is a child of some other context, you'll need to save all the way up the chain until you reach the root context.)

Related