0
votes

Context setup: Child (private queue) -> Parent (main queue) -> Persistent Store Coordinator

About 50% of the time when saving my child context, my parent/main context doesn't recognize the changes and therefore never saves to the persistent store.

func saveContext(context: NSManagedObjectContext, childThread: Bool) {
    if context.hasChanges {

        do {
            try context.save()
            print("saved on mainThread: \(!childThread)!")
        } catch {
            //...
        }

        if context.parentContext != nil { // private context
            dispatch_async(dispatch_get_main_queue(), {
                print("preparing to save main context")
                self.saveContext(context.parentContext!, childThread: false)
            })
        }
    } else {
        print("no changes seen")
    }
}

In other words, after I save successfully on the child context, my saveContext method prepares to save the context on the main thread, only to, about 50% of the time, fail and print out "no changes seen."

Is context.save() being executing asynchronously? Do I need to use something like a context saved notification? (I thought that wasn't necessary for the parent-child setup.)

1

1 Answers

0
votes

You should be using performBlock/performBlockAndWait to perform operations on contexts.