Firstly, sorry if my english is not perfect, i'm not a native english person ;) !
I'm working on an Application which retrieves EKEvent From iCal and add them to my App.
The purpose of the application is a calendar so :
The user retrieve iCal's EKEvent from the calendar he wants to.
The EKEvent are saved into an Entity named "Event".
The user can edit, add, delete event from the application - the EKEvent associate will be modified in iCal too.
Issue : when the user modify something in iCal, it has to be modified into my application so the only way i found is to retrieve all EKEvent from iCal - when the app become active - and copy it into a BackUp Entity named "EventBackup". When all EKEvent from iCal are well retrieved and saved into the "EventBackup" entity i copy the entity into my main Entity "Event".
I'm doing it succesfully in async with
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { });
But I have to keep using my application - so retrieving Event * from CoreData - while i'm doing the EventBackup... problem my application crash if i'm working on the CoreData.
Could you help on that way, or propose me something different than the way i'm doing.
Thanks a lot for helping me !
You should look at NSManagedObjectContext's performBlock: method. Specifically you should create a child context, make your changes in it on a background thread and then listen for the save notification to merge it into the parent context.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:nil];
NSManagedObjectContext *childContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[childContext setParentContext:self.managedObjectContext];
[childContext performBlock:^{
//Do everything here...
NSError *error = nil;
[context save:&error];
if (error) {
NSLog(@"Error saving child context:%@", error.localizedDescription);
}
}];
Listen for the child context to save and then save the main context.
- (void)managedObjectContextDidSave:(NSNotification *)notification
{
if ([notification object] != self.managedObjectContext) {
dispatch_sync(dispatch_get_main_queue(), ^{
[self.managedObjectContext save:nil];
});
}
}