Database Reference
In-Depth Information
context
.
persistentStoreCoordinator
=
psc
//4
let
documentsURL =
applicationDocumentsDirectory
()
let
storeURL =
documentsURL.
URLByAppendingPathComponent
(
"Dog Walk"
)
let
options =
[
NSMigratePersistentStoresAutomaticallyOption
:
true
]
var
error:
NSError
? =
nil
store
=
psc
.
addPersistentStoreWithType
(
NSSQLiteStoreType
,
configuration:
nil
,
URL: storeURL,
options: options,
error:&error)
if
store
==
nil
{
println
(
"Error adding persistent store:
\(error)
"
)
abort
()
}
}
The initializer is responsible for configuring each individual component in your Core
Data stack. It's a large chunk of code that probably looks very cryptic at the
moment, so let's go over each section in turn:
1. The first step is to load the managed object model from disk into a
NSManagedObjectModel
object. You do this by getting a URL to the
momd
directory
that contains the compiled version of the
.xcdatamodeld
file.
2. Once you've initialized
NSManagedObjectModel
, the next step is to create
NSPersistentStoreCoordinator
. Remember that the persistent store coordinator
mediates between the persistent store and
NSManagedObjectModel
. Initialize one
using the
NSManagedObjectModel
you just created.
3. The
NSManagedObjectContext
takes no arguments to initialize. However, it won't
be very useful until you connect it to an
NSPersistentStoreCoordinator
. You can
do this easily by setting the context's
persistentStoreCoordinator
property to the
persistent store coordinator you just created in the previous step.
4. The way you create a persistent store is a bit unintuitive—you don't initialize it
directly. Instead, the persistent store coordinator hands you an
NSPersistentStore
object as a side effect of attaching a persistent store type. You
simply have to specify the store type (
NSSQLiteStoreType
in this case), the URL
location of the store file and some configuration options.