Database Reference
In-Depth Information
going to need to create one or more child objects and associate them with the
NSManagedObject we are currently working on. Whether we are creating one or
many child objects, the steps are virtually identical. We will use a block to
perform the identical portions of the process and avoid ending up with two
copies of that code.
Therefore, the purpose of the block is to construct the new NSManagedObject
and recursively call -populateManagedObject:fromDictionary: for the new NSManagedOb-
ject . The block makes the rest of this method easier to follow and maintain.
Baseline/PPRecipes/PPRImportOperation.m
NSDictionary *relationshipsByName = [entity relationshipsByName];
NSManagedObject *destMO = nil;
for (NSString *key in relationshipsByName) {
id childStructure = [dict valueForKey:key];
if (!childStructure) continue ; //Relationship not populated
NSRelationshipDescription *relDesc = [relationshipsByName valueForKey:key];
NSEntityDescription *destEntity = [relDesc destinationEntity];
if (![relDesc isToMany]) { //ToOne
destMO = createChild(childStructure, destEntity, context);
[mo setValue:destMO forKey:key];
continue ;
}
NSMutableSet *childSet = [NSMutableSet set];
for (NSDictionary *childDict in childStructure) {
destMO = createChild(childDict, destEntity, context);
[childSet addObject:destMO];
}
[self setValue:childSet forKey:key];
}
}
With the attributes populated, we now need to populate the relationships.
We begin by grabbing the dictionary from the NSEntityDescription that describes
all of the relationships of our current NSManagedObject and iterating over them.
For each relationship, we check whether there is a value set. If there is no
value, then there is nothing to process. The iterator returns the key from the
dictionary, which is the name of the relationship (and also the name of the
accessor).
If there is a value to process, we next check whether the relationship is a to-
one or a to-many. If it is a to-many, we can invoke our block and create the
child NSManagedObject . We can then set the resulting NSManagedObject using KVC
and the key from our relationship dictionary.
 
 
 
Search WWH ::




Custom Search