Database Reference
In-Depth Information
//Returns immediately, cancel here if you want
} else {
println ( "Could not fetch \(error) , \(error!. userInfo ) " )
}
}
There's a lot that you haven't seen before, so let's cover it step by step:
1. Notice here than an asynchronous fetch request doesn't replace the regular fetch
request. Rather, you can think of an asynchronous fetch request as a wrapper
around the fetch request you already had.
2. To create an NSAsynchronousFetchRequest you need two things: a regular
NSFetchRequest and a completion handler. Your fetched venues are contained in
NSAsynchronousFetchResult 's finalResult property. Within the completion
handler, you update the venues property and reload the table view.
3. Specifying the completion handler is not enough! You still have to execute the
asynchronous fetch request. Once again, CoreDataStack 's context property
handles the heavy lifting for you. However, notice that the method you use is
different—this time, it's executeRequest() instead of the usual
executeFetchRequest() .
4. executeRequest() returns immediately. You don't need to do anything with the
return value since you're going to update the table view from within the
completion block. The return type is NSAsynchronousFetchResult .
Note: As an added bonus to this API, you can cancel the fetch request with
NSAsynchronousFetchResult 's cancel() method.
If you were to build and run the sample app at this point, it would crash on launch.
There are two more changes you need to make.
First, go to CoreDataStack.swift and replace context = NSManagedObjectContext()
with the following code:
context = NSManagedObjectContext (concurrencyType:
. MainQueueConcurrencyType )
A managed object context can have one of three concurrency types. If you don't
specify a concurrency type, it defaults to .ConfinementConcurrencyType . The
problem is that this concurrency type is an old pattern that is all but deprecated.
As such, asynchronous fetching doesn't work with the confinement concurrency
type, so you have to be explicit and set your concurrency type to
. MainQueueConcurrencyType .
Search WWH ::




Custom Search