Database Reference
In-Depth Information
void
(^savePrivate) (
void
) = ^{
NSError *error = nil;
ZAssert([private save:&error], @
"Error saving private moc: %@\n%@"
,
[error localizedDescription], [error userInfo]);
};
if
([private hasChanges]) {
if
(wait) {
[private performBlockAndWait:savePrivate];
}
else
{
[private performBlock:savePrivate];
}
}
}
Previously in our
-saveContext
method, we checked to make sure we had an
NSManagedObjectContext
and that it had changes. We can still check to see whether
we have an
NSManagedObjectContext
, since we create both of them at the same
time. However, we now need to check both the main
NSManagedObjectContext
and
the private
NSManagedObjectContext
for changes.
If the main
NSManagedObjectContext
has changes, we execute a
-performBlockAndWait:
to give the main
NSManagedObjectContext
all of the time that it needs to save.
When the main has finished saving (or if it didn't need a save), we check the
private context to see whether it also needs saving. When the private
NSMan-
agedObjectContext
needs a save, we perform that save on the private context's
queue. However, there are some situations in which we might want to block
on the save and others where we might want it to be asynchronous. For
example, when we are going into the background or terminating the applica-
tion, we will want to block. If we are doing a save while the application is still
running, we would want to be asynchronous. Fortunately, the
-saveContext:
method accepts a boolean that lets us know which method to call.
The only other alterations we need now are to change any calls from
-saveContext
to
-saveContext:
and pass in a boolean to determine whether the save blocks.
Updating Our PPRImportOperation
Another situation in which the parent-child context design provides a huge
performance gain is when we need to merge changes between contexts. There' s
a good example of this in our current application, in the
PPRImportOperation
.
Without the parent-child
NSManagedObjectContext
design, we must block the main
thread during our save of the import. If there is only one recipe coming in,
there probably won't be any issue. The save will be fast enough that the user
won't notice. However, if we import hundreds of recipes, the save would cause
a noticeable delay.