Database Reference
In-Depth Information
In this portion of the code, we grab a reference to a global queue with a default
priority. Then we add a block to be executed on that queue that will handle
the addition of the
NSPersistentStore
to the
NSPersistentStoreCoordinator
.
Inside of that block, we first determine where we want to store the file associ-
ated with our
NSPersistentStore
. In this example, we are going to put it into the
Documents directory that is part of the application sandbox. If we were
working on OS X, we could put it in the Application Support folder or anywhere
else that was appropriate. We resolve this path using the
NSFileManager
and
call its
-URLsForDirectory:inDomains:
method, which will return an array of
NSURL
instances. We call
-lastObject
on that array to retrieve the last
NSURL
. We then
append the filename for our
NSPersistentStore
to the end of that
NSURL
.
With the location of the store now resolved, we can add the
NSPersistentStore
to
the
NSPersistentStoreCoordinator
. We do this with a call to
-addPersistentStoreWithType:
configuration: URL: options: error:
. This is a complex method call, so let's break it
down by parameter. There are five in all.
• The first parameter is
Type
. This tells the
NSPersistentStoreCoordinator
what type
of store we want initialized. In this case, we are passing
NSSQLiteStoreType
to indicate we want a SQLite store. This is the parameter to change if we
want to use another store type.
• The second parameter is
configuration
. This is an advanced setting that
allows us to partition our data model into different configurations for dif-
ferent uses. Since we are not partitioning our data model at this time, we
will pass
nil
, which tells the
NSPersistentStoreCoordinator
that we want to use
the default configuration.
• The third parameter,
URL
, accepts the
NSURL
for the store. We pass in the
NSURL
that we resolved earlier.
• The fourth parameter,
options
, allows us to change the behavior of the
NSPersistentStore
. This parameter is used during versioning, during iCloud
configuration, and for on-disk encryption. We are not using any of these
features at this time, so we pass
nil
here as well.
• The last parameter,
error
, is used when something goes wrong with the
addition of the
NSPersistentStore
. It is tempting to pass
nil
here as well, but
I strongly advise against it. This is the only indicator when something
goes wrong. I recommend passing a pointer to an
NSError
variable so that
we can interrogate the error if something goes wrong.
This call will either return a
NSPersistentStore
or return
nil
. If it returns
nil
, that
means something failed, and we need to interrogate the error. Since we do