In my project I should download a JSON file made in this way:
[{"id":"2","n":"One"},{"id":"2","n":"Two"},{"id":"2","n":"Three"},...]
my code is this:
- (void) startPopulate:(NSArray *)array{
NSManagedObjectContext *context = [[self sharedAppDelegate] managedObjectContext];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Myentity"];
NSError *error = nil;
for (id element in array){
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"id == %@",[element objectForKey:@"id"]]];
Myentity *myE = [[context executeFetchRequest:fetchRequest error:&error] lastObject];
//update
if (myE != nil){
myE.id_e = [element objectForKey:@"id"];
myE.name = [element objectForKey:@"n"];
}
//new element
else{
Myentity *myE = [NSEntityDescription insertNewObjectForEntityForName:@"Myentity" inManagedObjectContext:context];
myE.name = [element objectForKey:@"n"];
myE.id_e = [element objectForKey:@"id"];
}
}
if (![context save:&error]) {
NSLog(@"couldn't save: %@", [error localizedDescription]);
}
else{
NSLog(@"DB UPDATED");
}
}
As you can see I pass at the method the array of dictionaries and I check if the entity exist or not. It work fine and I have not particulars problems. The 'problem', if it's the way to call it, is that I have 12000 element and this method run for about 53 seconds. It's very very slow. What type of solution can I adopt to make it more quick? Or I should just put this method inside a background process? thanks