Database Reference
In-Depth Information
Once we have the data in a JSON structure, we must check whether the top-
level object is an NSArray or an NSDictionary . Adding this check makes the import
operation more flexible and capable of handling the imported recipes. If the
top-level object is an NSDictionary , we know there is a single recipe being
imported and begin the import operation. If the top-level object is an NSArray ,
we iterate over the array and construct a recipe for each included dictionary.
For each dictionary (whether there are one or many), we construct an
NSManagedObject and pass both the dictionary and the NSManagedObject into -popu-
lateManagedObject:fromDictionary: .
Baseline/PPRecipes/PPRImportOperation.m
- ( void )populateManagedObject:(NSManagedObject*)mo
fromDictionary:(NSDictionary*)dict
{
NSManagedObjectContext *context = [mo managedObjectContext];
NSEntityDescription *entity = [mo entity];
NSArray *attKeys = [[entity attributesByName] allKeys];
NSDictionary *atttributesDict = [dict dictionaryWithValuesForKeys:attKeys];
[mo setValuesForKeysWithDictionary:atttributesDict];
In the first part of -populateManagedObject:fromDictionary: , we want to populate all
the attributes of the NSManagedObject . The process is the reverse of what we
accomplished in the PPRExportOperation . Here are the steps:
1.
We grab an NSArray of all the attribute names for the entity.
2.
We then retrieve an NSDictionary from the passed-in NSDictionary of only those
attributes and their associated values.
3.
We take the resulting dictionary and hand it off to the NSManagedObject via
the KVC method -setValuesForKeysWithDictionary: .
Baseline/PPRecipes/PPRImportOperation.m
NSManagedObject* (^createChild)(NSDictionary *childDict,
NSEntityDescription *destEntity,
NSManagedObjectContext *context);
createChild = ^(NSDictionary *childDict, NSEntityDescription *destEntity,
NSManagedObjectContext *context) {
NSManagedObject *destMO = nil;
destMO = [[NSManagedObject alloc] initWithEntity:destEntity
insertIntoManagedObjectContext:context];
[self populateManagedObject:destMO fromDictionary:childDict];
return destMO;
};
The next step is to create a block to avoid repeating ourselves later in this
method. When we are dealing with the creation of the relationships, we are
 
 
 
Search WWH ::




Custom Search