I use the following code to load data from a web service and store it in a Core Data DB.
dispatch_queue_t fetchQ = dispatch_queue_create("fetcher", NULL);
dispatch_async(fetchQ, ^{
NSArray *list = [WebService loadData];
dispatch_sync(dispatch_get_main_queue(), ^{
if (list != nil) {
for (NSDictionary *data in list) {
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Object" inManagedObjectContext:appDelegate.coreDataDatabase.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id = %i", [[data objectForKey:@"id"] integerValue]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *data = [appDelegate.coreDataDatabase.managedObjectContext executeFetchRequest:request error:&error];
Object *object = [data objectAtIndex: 0];
if (object == nil) {
object = [NSEntityDescription insertNewObjectForEntityForName:@"Object" inManagedObjectContext:appDelegate.coreDataDatabase.managedObjectContext];
object.id = [NSNumber numberWithInteger:[[data objectForKey:@"id"] integerValue]];
}
object.name = [data objectForKey:@"name"];
}
[appDelegate.coreDataDatabase saveToURL:appDelegate.coreDataDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];
}
});
});
dispatch_release(fetchQ);
The code is simplified, but it should represent the sequence. The access to the web service runs in the background. After that, the store is called in the main thread. Should actually OK, right?
Unfortunately, the whole works not on all devices. On all my devices and most of the other, there is no problem. On some but apparently so, because unfortunately there are some negative Bewertugnen in the store and a couple of questions. The problem is that he finds an already existing record in the DB and not constantly new investing
Thanks for your help, Stefan