Database Reference
In-Depth Information
executed so far has blocked the main thread while you waited for your results to
come back.
When you block the main thread, it makes the screen unresponsive to incoming
touches and creates a slew of other problems. You haven't felt this blocking of the
main thread because you've made simple fetch requests that only fetch a few
objects at a time.
Since the beginning of Core Data, the framework has given developers several
techniques to perform fetches in the background. New in iOS 8, Core Data now has
an API for performing long-running fetch requests in the background and getting a
completion callback when the fetch is completed.
Let's see this new API in action. Go back to
ViewController.swift
and add the
following property:
var
asyncFetchRequest:
NSAsynchronousFetchRequest
!
There you have it. The new class responsible for this asynchronous magic is aptly
called
NSAsynchronousFetchRequest
. Don't be fooled by its name, though. It isn't
directly related to
NSFetchRequest
; it's actually a subclass of
NSPersistentStoreRequest
.
Go to
viewDidLoad()
and re-implement it as shown below:
override
func
viewDidLoad() {
super
.
viewDidLoad
()
//1
fetchRequest
=
NSFetchRequest
(entityName:
"Venue"
)
//2
asyncFetchRequest
=
NSAsynchronousFetchRequest
(fetchRequest:
fetchRequest
)
{ [unowned
self
] (result:
NSAsynchronousFetchResult
! )
-> Void
in
self
.
venues
= result.
finalResult
as
[
Venue
]
self
.
tableView
.
reloadData
()
}
//3
var
error:
NSError
?
let
results =
coreDataStack
.
context
.
executeRequest
(
asyncFetchRequest
,
error: &error)
if
let
persistentStoreResults = results {