populate CoreData data model from JSON files prior to app start
Posted
by
johannes_d
on Stack Overflow
See other posts from Stack Overflow
or by johannes_d
Published on 2012-09-15T15:01:05Z
Indexed on
2012/09/15
15:37 UTC
Read the original article
Hit count: 232
I am creating an iPad App that displays data I got from an API in JSON format. My Core Data model has several entities(Countries, Events, Talks, ...). For each entity I have one .json file that contains all instances of the entity and its attributes as well as its relationships.
I would like to populate my Core Data data model with these entities before the start of the App (otherwise it takes about 15 minutes for the iPad to create all the instances of the entities from the several JSON files using factory methods).
I am currently importing the data into CoreData like this:
-(void)fetchDataIntoDocument:(UIManagedDocument *)document
{
dispatch_queue_t dataQ = dispatch_queue_create("Data import", NULL);
dispatch_async(dataQ, ^{
//Fetching data from application bundle
NSURL *tedxgroupsurl = [[NSBundle mainBundle] URLForResource:@"contries" withExtension:@"json"];
NSURL *tedxeventsurl = [[NSBundle mainBundle] URLForResource:@"events" withExtension:@"json"];
//converting the JSON files to NSDictionaries
NSError *error = nil;
NSDictionary *countries = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:countriesurl] options:kNilOptions error:&error];
countries = [countries objectForKey:@"countries"];
NSDictionary *events = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:eventsurl] options:kNilOptions error:&error];
events = [events objectForKey:@"events"];
//creating entities using factory methods in NSManagedObject Subclasses (Country / Event)
[document.managedObjectContext performBlock:^{
NSLog(@"creating countries");
for (NSDictionary *country in countries) {
[Country countryWithCountryInfo:country inManagedObjectContext:document.managedObjectContext]; //creating Country entities
}
NSLog(@"creating events");
for (NSDictionary *event in events) {
[Event eventWithEventInfo:event inManagedObjectContext:document.managedObjectContext]; // creating Event entities
}
NSLog(@"done creating, saving document");
[document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL];
}];
});
dispatch_release(dataQ);
}
This combines the different JSON files into one UIManagedDocument which i can then perform fetchRequests on to populate tableViews, mapView, etc.
I'm looking for a way to create this document outside my application & add it to the mainBundle. Then I could copy it once to the apps DocumentsDirectory and be able I use it (instead of creating the Document within the app from the original JSON files). Any help is appreciated!
© Stack Overflow or respective owner