Core Data Import from Plist


/ Published in: Objective C
Save to your folder(s)

Just change the filename "courses" to that of your own and the entity name "Course" to your own.


Copy this code and paste it in your HTML
  1. NSManagedObjectModel *mom = [self managedObjectModel];
  2. NSDictionary *attrs = [[[mom entitiesByName] objectForKey:@"Course"] attributesByName];
  3. NSArray *keyedValues = [[NSArray alloc] initWithContentsOfFile:
  4. [[NSBundle mainBundle] pathForResource:@"courses" ofType:@"plist"]
  5. ];
  6.  
  7. for( NSDictionary *keyedValueDict in keyedValues ) {
  8. NSManagedObject *mObj = [NSEntityDescription insertNewObjectForEntityForName:@"Course" inManagedObjectContext:[self managedObjectContext]];
  9. for (NSString *attribute in attrs) {
  10. id value = [keyedValueDict objectForKey:attribute];
  11. if (value == nil) {
  12. // Don't attempt to set nil, or you'll overwite values in self that aren't present in keyedValues
  13. continue;
  14. }
  15. NSAttributeType attributeType = [[attrs objectForKey:attribute] attributeType];
  16. if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]])) {
  17. value = [value stringValue];
  18. } else if (((attributeType == NSInteger16AttributeType) || (attributeType == NSInteger32AttributeType) || (attributeType == NSInteger64AttributeType) || (attributeType == NSBooleanAttributeType)) && ([value isKindOfClass:[NSString class]])) {
  19. value = [NSNumber numberWithInteger:[value integerValue]];
  20. } else if ((attributeType == NSFloatAttributeType) && ([value isKindOfClass:[NSString class]])) {
  21. value = [NSNumber numberWithDouble:[value doubleValue]];
  22. }
  23. [mObj setValue:value forKey:attribute];
  24. NSLog(@"Value %@ for Key %@", value, attribute);
  25. }
  26.  
  27. }
  28. NSError *error;
  29. [[self managedObjectContext] save:&error];

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.