Database Reference
In-Depth Information
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:
@selector
(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:localMOC];
Unlike its
PPRExportOperation
counterpart, the
PPRImportOperation
makes changes
to the
NSManagedObjectContext
; we'll need to observe the changes and consume
them in the primary
NSManagedObjectContext
.
NSError *error = nil;
id recipesJSON = nil;
recipesJSON = [NSJSONSerialization JSONObjectWithData:[self incomingData]
options:0
error:&error];
if
(!recipesJSON) {
[self completionBlock](NO, error);
return
;
}
NSManagedObject *recipeMO = nil;
if
([recipesJSON isKindOfClass:[NSDictionary class]]) {
recipeMO = [NSEntityDescription insertNewObjectForEntityForName:@
"Recipe"
inManagedObjectContext:localMOC];
[self populateManagedObject:recipeMO fromDictionary:recipesJSON];
return
;
}
else
{
ZAssert([recipesJSON isKindOfClass:[NSArray class]],
@
"Unknown structure root: %@"
, [recipesJSON class]);
for
(id recipeDict in recipesJSON) {
ZAssert([recipeDict isKindOfClass:[NSDictionary class]],
@
"Unknown recipe structure: %@"
, [recipeDict class]);
recipeMO = [NSEntityDescription insertNewObjectForEntityForName:@
"Recipe"
inManagedObjectContext:localMOC];
[self populateManagedObject:recipeMO fromDictionary:recipeDict];
}
ZAssert([localMOC save:&error], @
"Error saving import context: %@\n%@"
,
[error localizedDescription], [error userInfo]);
}
}
The last portion of the
-main
is where the real work gets done. We start by
using the
NSJSONSerializer
to convert the
NSData
into a JSON structure. If that
conversion fails, we call the completion block and finish the operation.