Database Reference
In-Depth Information
error:&error];
if
(!store) {
ALog(@
"Error adding persistent store to coordinator %@\n%@"
,
[error localizedDescription], [error userInfo]);
//Present a user facing error
}
dispatch_sync(dispatch_get_main_queue(), ^{
[self contextInitialized];
});
});
In this code block, we define the path for our SQLite file and gain a reference
to the
NSPersistentStoreCoordinator
. From there, we add the
NSPersistentStore
to the
NSPersistentStoreCoordinator
. Assuming that is successful, we push another block
back to the main queue and inform the application that the Core Data stack
has been completed and is ready for use.
The reason we grab a fresh reference to the
NSPersistentStoreCoordinator
is one of
safety. If we were to use the reference from the outer method, we would be
incrementing the retain count of the
NSPersistentStoreCoordinator
and potentially
causing an unnecessary reference count issue. Since we can easily obtain a
fresh reference to it, there is no reason to use the reference from the outer
method.
Likewise, once we have completed the construction of the
NSPersistentStoreCoor-
dinator
, we want to be on the main thread (aka the UI Thread) when we call
-contextInitialized
so that the rest of the
AppDelegate
does not need to dance with
threads. Keeping all of the thread jumping in one place makes it easier to
maintain.
6.3
Consuming Changes from iCloud
Whether we are using a standard Core Data stack or a
UIManagedDocument
, we
need to know when changes come in from iCloud. Changes will always come
in asynchronously, and our
NSManagedObjectContext
won't know about them. It
is our responsibility to notify our
NSManagedObjectContext
of any incoming
changes. To do that, we first need to listen for the change notification via the
NSNotificationCenter
.
NSString *name = nil;
name = NSPersistentStoreDidImportUbiquitousContentChangesNotification;
[center addObserver:self
selector:
@selector
(mergePSCChanges:)
name:name
object:[[self managedObjectContext] persistentStoreCoordinator]];
}