Chapter 10: private context book example

According to the Book we must use coreDataStack.context in this call:

privateContext.performBlock { () → Void in
let results: [AnyObject]
do {
results = try self.coreDataStack.context.executeFetchRequest(self.surfJournalFetchRequest())
} catch {
let nserror = error as NSError
print(“ERROR: (nserror)”)
results = []
}

However, I used privateContext in this call:

privateContext.performBlock { () → Void in
let results: [AnyObject]
do {
results = try privateContext.executeFetchRequest(self.surfJournalFetchRequest())
} catch {
let nserror = error as NSError
print(“ERROR: (nserror)”)
results = []
}

Both options worked fine. But using privateContext seems more logical to me. Or am I missing something? Thanks.

The whole

childContext.parentContext = mainContext

vs

childContext.persistentStoreCoordinator = mainContext.persistentStoreCoordinator

is confusing to me.

But I think since they both use the same persistentStoreCoordinator in the example, both will do the same thing. If it was rather like so

childContext.parentContext = mainContext // (mainContext being coreDataStack.context)

then you would rather use

results = try mainContext.executeFetchRequest(self.surfJournalFetchRequest())

since you’re using the privateContext to performBlock, the block will be performed on the privateQueue, but you’ll have to use the mainContext to fetch/update/remove/add since you want to have the latest changes.

self.coreDataStack.context is called from the ViewController, where that variable was declared. It is the main object context.

privateContext is simply pointing to the NSManagedObjectContext as declared on p246 of the book inside the JournalListViewController.swift but with a private queue dispatch.

The difference is the private context. The private queue is used to move work off of the Main queue, so as to not block it. By moving the Export operation from the Main queue (where it is usually performed unless otherwise specified) to the private queue, your app remains responsive even after tapping the Export button.

@marciokoko
So when should you set private context’s persistentStoreCoordinator to main’s persistentStoreCoordinator and when should you set private context’s parentContext to mainContext? What’s the difference?