Skip to content

Instantly share code, notes, and snippets.

@0xc010d
Created February 19, 2011 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xc010d/835215 to your computer and use it in GitHub Desktop.
Save 0xc010d/835215 to your computer and use it in GitHub Desktop.
+ (NSManagedObject *)managedObjectFromStructure:(NSDictionary *)structureDictionary
entityName:(NSString *)entityName
withManagedObjectContext:(NSManagedObjectContext *)context {
NSMutableDictionary *mutableStructureDictionary = [structureDictionary mutableCopy];
NSManagedObject *managedObject = nil;
NSManagedObjectModel *model = [context.persistentStoreCoordinator managedObjectModel];
for (NSString *property in [mutableStructureDictionary allKeys]) {
NSString *fetchRequestName = [NSString stringWithFormat:@"%@_%@", entityName, property];
if ([model fetchRequestTemplateForName:fetchRequestName]) {
NSDictionary *fetchDictionary = [NSDictionary dictionaryWithObject:[mutableStructureDictionary objectForKey:property] forKey:property];
NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:fetchRequestName substitutionVariables:fetchDictionary];
NSArray *results = [context executeFetchRequest:fetchRequest error:NULL];
if ([results count]) {
managedObject = [results objectAtIndex:0];
}
}
}
if (!managedObject) {
managedObject = [NSEntityDescription insertNewObjectForEntityForName:entityName
inManagedObjectContext:context];
}
NSDictionary *relationshipsByName = [[managedObject entity] relationshipsByName];
for (NSString *relationshipName in [relationshipsByName allKeys]) {
NSRelationshipDescription *relationshipDescription = [relationshipsByName objectForKey:relationshipName];
NSString *relationshipEntityName = [[relationshipDescription destinationEntity] name];
if (![relationshipDescription isToMany]) {
NSDictionary *childStructureDictionary = [mutableStructureDictionary objectForKey:relationshipName];
NSManagedObject *childObject = [[self class] managedObjectFromStructure:childStructureDictionary
entityName:relationshipEntityName
withManagedObjectContext:context];
[managedObject setValue:childObject forKey:relationshipName];
} else {
NSMutableSet *relationshipSet = [managedObject mutableSetValueForKey:relationshipName];
NSArray *relationshipArray = [mutableStructureDictionary objectForKey:relationshipName];
for (NSDictionary *childStructureDictionary in relationshipArray) {
NSManagedObject *childObject = [[self class] managedObjectFromStructure:childStructureDictionary
entityName:relationshipEntityName
withManagedObjectContext:context];
[relationshipSet addObject:childObject];
}
}
[mutableStructureDictionary removeObjectForKey:relationshipName];
}
[managedObject setValuesForKeysWithDictionary:mutableStructureDictionary];
[mutableStructureDictionary release];
return managedObject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment