Database Reference
In-Depth Information
//1
let
fetchRequest1 =
NSFetchRequest
()
let
entity =
NSEntityDescription
.
entityForName
(
"Person"
,
inManagedObjectContext:
managedObjectContext
!)
fetchRequest1.
entity
= entity!
//2
let
fetchRequest2 =
NSFetchRequest
(entityName:
"Person"
)
//3
let
fetchRequest3 =
managedObjectModel
.
fetchRequestTemplateForName
(
"peopleFR"
)
//4
let
fetchRequest4 =
managedObjectModel
.
fetchRequestFromTemplateWithName
(
"peopleFR"
,
substitutionVariables: [
"NAME"
:
"Ray"
])
Let's go through them in turn:
1. In the first example, you initialize an instance of
NSFetchRequest
as if it were any
other object. At a minimum, you must specify an
NSEntityDescription
for the
fetch request. In this case, the entity is
Person
. You initialize an instance of
NSEntityDescription
and use it to set the fetch request's
entity
property.
2. Here, you use
NSFetchRequest
's convenience initializer. It initializes a new fetch
request and sets its entity property in one step. You simply need to provide a
string for the entity name rather than a full-fledged
NSEntityDescription
.
3. In the third example, you retrieve your fetch request from your
NSManagedObjectModel
. You can configure and store commonly used fetch requests
in Xcode's data model editor. You'll learn how to do this later in the chapter.
4. The last case is similar to the third. You get a fetch request from your managed
object model, but this time, you pass in some extra variables. These
“substitution” variables are used in a predicate to refine your fetched results.
The first two examples are the simple cases you've already seen. You'll see even
more of these simple cases in the rest of this chapter, in addition to stored fetch
requests and other tricks of
NSFetchRequest
!
Introducing the Bubble Tea app
This chapter's sample project is a bubble tea app. For those of you who don't know
about bubble tea (also known as “boba tea”), it is a Taiwanese tea-based drink that
contains large tapioca pearls. It's very yummy!