I've a project using Core Data with a default AppDelegate. I've the following thread in my code, where the image for my NSManagedObject WSObject
is downloaded. As you will notice, I'm creating a new NSManagedObjectContext
for this background thread. I've tried to read the different documentations and other forum topics on the web, but cannot understand how I can notify my main context in the AppDelegate after my object is saved in the background context.
- (void) downloadImageForObjectID:(NSManagedObjectID*)objectID {
dispatch_queue_t imageDownloaderQueue = dispatch_queue_create("imagedownloader", NULL);
dispatch_async(imageDownloaderQueue, ^{
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
context.persistentStoreCoordinator = [(AppDelegate *)[[UIApplication sharedApplication] delegate] persistentStoreCoordinator];
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
WSObject *item = (WSObject*)[context objectWithID:objectID];
item.image.data = [item.image download];
if ([context hasChanges]) {
NSError *error = nil;
[context save:&error];
}
});
dispatch_release(imageDownloaderQueue);
}
Could someone please tell me what to add to this method and the AppDelegate to get this working? As far as I understand a NSManagedObjectContextDidSaveNotification
is sent when I save the context in my background thread. What code should I add to my AppDelegate to listen to this notification and what to do when the notification is received?
EDIT1: I've added the observer to the background thread.
if ([context hasChanges]) {
NSError *error = nil;
NSManagedObjectContext *mainContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeHandler:) name:NSManagedObjectContextDidSaveNotification object:mainContext];
[context save:&error];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:mainContext];
}
But the mergeHandler
in the AppDelegate is never called.