Database Reference
In-Depth Information
To initialize the
NSManagedObjectModel
, we first need to locate it within the
application bundle. We call upon the
NSBundle
and retrieve the
-mainBundle
,
which represents the application bundle. From there, we call
-URLForResource:
withExtension:
using the name of our data model—in this case
PPRecipes
—and the
extension
.momd
. We use one of the macros discussed in
Appendix 2,
Macros
in the Precompiled Header
, on page 221
, and we verify that we did receive a
NSURL
. We then initialize the
NSManagedObjectModel
with that
NSURL
. We again
verify that everything worked correctly by checking the new instance against
nil
.
And that's all that is involved in constructing the
NSManagedObjectModel
. Our
next step is to construct the
NSPersistentStoreCoordinator
, which uses the
NSManage-
dObjectModel
we just initialized.
1.2
NSPersistentStoreCoordinator
The
NSPersistentStoreCoordinator
is the true maestro of Core Data. The
NSPersis-
tentStoreCoordinator
is responsible for persisting, loading, and caching data. Think
of the
NSPersistentStoreCoordinator
as the heart of Core Data. Having said this, we
do very little work with the
NSPersistentStoreCoordinator
directly. We work with it
upon initialization, but we almost never touch it again over the life of the
application.
As part of our initialization, we perform two steps with the
NSPersistentStoreCoor-
dinator
. First, we initialize it, which requires a valid
NSManagedObjectModel
. Once
it is initialized, we add one or more
NSPersistentStore
instances. An
NSPersistentStore
is a representation of a location in which the data is saved/persisted. Typically,
this persistence is done to disk. However, that step is not required; it could
be in memory or even over the network. For now, let's focus on disk persis-
tence. The
NSPersistentStore
is responsible for describing the file format used.
This file format can be one of several: SQLite, binary, or atomic. (There's also
an XML store for OS X, but I do not recommend using it because it is not
available on iOS, nor does it perform very well.) To keep our focus, we will
use the SQLite format in this first iteration of our application and explore the
other formats later in the topic.
In previous versions of Core Data and the sample projects, the initialization
of the
NSPersistentStoreCoordinator
and the addition of the
NSPersistentStore
were done
in a single method. This example tended to lead to a number of issues for
developers because they did not fully understand the impact of the example.
Therefore, we are going to do this initialization in a more complex way, but
it will be a way that will not paint us into a corner.