Skip to content

Instantly share code, notes, and snippets.

@0xc010d
Created February 18, 2011 16:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xc010d/833919 to your computer and use it in GitHub Desktop.
Save 0xc010d/833919 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 = [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;
}
@sergeyzenchenko
Copy link

and what is problem?

@0xc010d
Copy link
Author

0xc010d commented Feb 19, 2011

I'd like you just to check this code :)

The first mistake I've found is that I need to use entityName except of entityClassName. So this code wouldn't work if entityName differs from its className.

And also, there's no check if such entity already exist. And even more, I have no idea on what's the correct way to add it :)

@sergeyzenchenko
Copy link

ok, I'll review it today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment