Database Reference
In-Depth Information
- (BOOL)save:(NSError**)error;
{
NSManagedObjectContext *moc = [self managedObjectContext];
if
(!moc)
return
YES;
if
(![moc hasChanges])
return
YES;
//Grab a reference to all of the objects we will need to work with
NSSet *deleted = [moc deletedObjects];
NSMutableSet *deletedPaths = [NSMutableSet set];
for
(NSManagedObject *object in deleted) {
if
(![object isKindOfClass:[PPRecipe class]])
continue
;
[deletedPaths addObject:[object valueForKey:@
"metadataFilename"
]];
}
NSMutableSet *updated = [NSMutableSet setWithSet:[moc insertedObjects]];
[updated unionSet:[moc updatedObjects]];
//Save the context
if
(![moc save:error]) {
return
NO;
}
return
[self updateMetadataForObjects:updated
andDeletedObjects:deletedPaths
error:error];
}
In this new
-save:
method, we are doing a couple of things before calling save
on the
NSManagedObjectContext
. Since the
NSManagedObjectContext
knows what objects
have been deleted, updated, or inserted, we want to grab a reference to that
information before the
-save:
occurs. Once the
-save:
is complete, that informa-
tion is no longer available. Therefore, we grab a reference to the
NSSet
f
deleted objects, updated objects, and inserted objects. Because the deleted
objects will be, well, deleted once the
-save:
is performed, we want to extract
the information we care about beforehand. So, we loop over the deleted objects
looking for
Recipe
instances. When we find one, we extract its
metadataFilename
and store it in a new
NSMutableSet
. In addition, since we will be doing the same
thing to the inserted and the updated objects, we merge them into one set.
Once we have that information, we go ahead and save the context. If the save
fails, we just abort and let the calling code handle the error. When the save
is successful, it is time to update the metadata.
if
((!updatedObjects || ![updatedObjects count]) &&
(!deletedObjects || ![deletedObjects count]))
return
YES;
NSString *path = [self metadataFolder:error];