Database Reference
In-Depth Information
contents. This method,
-mergeChangesFromContextDidSaveNotification:
, will update
the
NSManagedObjectContext
with the changes and also notify any observers of
those changes. This means our main
NSManagedObjectContext
can be updated
with a single call whenever the background
NSManagedObjectContext
instances
perform a save, and our user interface will be updated automatically.
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:
@selector
(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:localMOC];
In this example, we listen for an
NSManagedObjectContextDidSaveNotification
and call
-contextDidSave:
whenever the notification is received. Also note that we're
interested only in notifications generated from our own
localMOC
; this helps to
avoid polluting the main
NSManagedObjectContext
with duplicate merges.
- (
void
)contextDidSave:(NSNotification*)notification
{
NSManagedObjectContext *moc = [self mainContext];
void
(^mergeChanges) (
void
) = ^ {
[moc mergeChangesFromContextDidSaveNotification:notification];
};
if
([NSThread isMainThread]) {
mergeChanges();
}
else
{
dispatch_sync(dispatch_get_main_queue(), mergeChanges);
}
}
When we receive a change notification, the only thing we need to do with it
is hand it off to the primary
NSManagedObjectContext
for consumption. However,
the main
NSManagedObjectContext
needs to consume that notification on the main
thread. To do this, we create a simple block and either call that block directly
(if we are on the main thread) or pass it off to the main thread via a dispatch
_sync if we are not on the main thread.
It should be noted that this call can take a human-perceivable amount of
time. In fact, prior to iOS 6.0 and OS X 10.8 Mountain Lion, this was one of
the greatest performance bottlenecks of Core Data that could not be avoided.
Fortunately, as we discuss in
Chapter 4,
Performance Tuning
, on page 61
,
applications targeting those platforms or newer have a solution.