I have a process I run periodically on a background thread that receives changes from a remote server and either creates, updates, or deletes records in a core data table locally. The creates and updates work great. Deletes do not seem to be processed at all. I’m sure I’m missing something dumb. Some code:
The queue I’m using is defined thusly:
self.concurrentQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
An NSTImer is setup that calls the following selector on a regular basis:
-(void)poll {
void(^blkSyncDeletedItems)(void)=^{
if ([PFUser currentUser]) {
AN3AppDelegate* theDelegate=[[UIApplication sharedApplication]delegate];
NSManagedObjectContext* blkmoc=[[NSManagedObjectContext alloc]init];
[blkmoc setPersistentStoreCoordinator:[theDelegate persistentStoreCoordinator]];
NSNotificationCenter* notify=[NSNotificationCenter defaultCenter];
[notify addObserver:theDelegate selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:blkmoc];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Deleted" inManagedObjectContext:blkmoc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSError* error=nil;
NSArray *array = [blkmoc executeFetchRequest:request error:&error];
... look up some data on the remote server, not manipulating objects in array...
for (int i=0; i<[array count]; i++) {
Deleted* aDelete=[array objectAtIndex:i];
[blkmoc deleteObject:aDelete];
}
[blkmoc release];
[[NSNotificationCenter defaultCenter]removeObserver:theDelegate];
};
dispatch_sync(concurrentQueue, blkSyncDeletedItems);
}
Finally, mergeChanges looks like this:
-(void)mergeChanges:(NSNotification *)notification {
NSLog(@"AppDelegate: merging changes.");
[[self managedObjectContext]performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES];
}
As I said, I have other blocks that are dispatched to the concurrentQueue that do updates and creates, using very similar code (same setup at beginning and end of block) and they work fine. When the deletes are ‘processed’, the mergeChanges method is never called.
Everything is called with dispatch_sync so supposedly things are done before the next block is called.
What am I doing wrong?
Thanks
You need to call
-[NSManagedObjectContext save:].