Database Reference
In-Depth Information
Exporting on a private queue
You want the UI to continue to work while the export is happening. To fix the UI
problem, you'll perform the export operation on a private background queue
instead of on the main queue.
Open
JournalListViewController.swift
and find the following code in
exportCSVFile
:
var
fetchRequestError:
NSError
? =
nil
let
results =
coreDataStack
.
context
.
executeFetchRequest
(
self
.
surfJournalFetchRequest
(),
error: &fetchRequestError)
if
results ==
nil
{
println
(
"ERROR:
\(fetchRequestError)
"
)
}
As you saw earlier, this code retrieves all of the journal entries by calling
executeFetchRequest
on the managed object context.
Now replace it with the following:
// 1
let
privateContext =
NSManagedObjectContext
(
concurrencyType: .
PrivateQueueConcurrencyType
)
privateContext.
persistentStoreCoordinator
=
coreDataStack
.
context
.
persistentStoreCoordinator
// 2
privateContext.
performBlock
{ () -> Void
in
// 3
var
fetchRequestError:
NSError
? =
nil
let
results = privateContext.
executeFetchRequest
(
self
.
surfJournalFetchRequest
(),
error: &fetchRequestError)
if
results ==
nil
{
println
(
"ERROR:
\(fetchRequestError)
"
)
}
Let's go through the new code, which utilizes a new managed object context, step
by step:
1. First, you create a new managed object context called
privateContext
with a
concurrency type of
PrivateQueueConcurrencyType
, which specifies that the
context will be associated with a private dispatch queue. Once you've created the
new context, you assign it the same persistent store coordinator as the main
managed object context.