Created
February 18, 2011 16:27
-
-
Save 0xc010d/833919 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (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; | |
} |
ok, I'll review it today.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)