Database Reference
In-Depth Information
NSPersistentStoreCoordinator *psc = nil;
psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
ZAssert(psc, @
"Failed to initialize persistent store coordinator"
);
In this first bit of code, we initialize the
NSPersistentStoreCoordinator
and pass it
the
NSManagedObjectModel
that we previously initialized. This call returns imme-
diately, and therefore we can do it inline as part of the start-up of the
application.
Adding one or more
NSPersistentStore
instances to the
NSPersistentStoreCoordinator
,
however, can take an unknown amount of time. The reason for the unpre-
dictability is that we could be performing a migration during the call (as
discussed in
Chapter 3,
Versioning and Migration
, on page 37
), or we could
be linking and updating with iCloud (as discussed in
Chapter 6,
Using iCloud
,
on page 99
). If either of those situations occurs, the addition of the
NSPersis-
tentStore
can delay the launch of the application to the point of providing a
poor user experience or, worse, being terminated by the operating system.
To avoid either of these situations, we want to add the
NSPersistentStore
on a
background queue so that the application can finish launching while we
perform our start-up.
dispatch_queue_t queue = NULL;
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *directoryArray = [fileManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask];
NSURL *storeURL = nil;
storeURL = [directoryArray lastObject];
storeURL = [storeURL URLByAppendingPathComponent:@
"PPRecipes.sqlite"
];
NSError *error = nil;
NSPersistentStore *store = nil;
store = [psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error];
if
(!store) {
ALog(@
"Error adding persistent store to coordinator %@\n%@"
,
[error localizedDescription], [error userInfo]);
//Present a user facing error
}