CoreData不处理在后台线程上执行时删除

时间:2012-01-13 03:51:19

标签: objective-c ios multithreading core-data objective-c-blocks

我有一个进程,我定期在后台线程上运行,该线程从远程服务器接收更改,并在本地创建,更新或删除核心数据表中的记录。创建和更新工作很棒。删除似乎根本没有被处理。我确定我错过了一些愚蠢的东西。一些代码:

我正在使用的队列是这样定义的:

self.concurrentQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

设置NSTImer,定期调用以下选择器:

-(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);
}

最后,mergeChanges看起来像这样:

-(void)mergeChanges:(NSNotification *)notification {
    NSLog(@"AppDelegate: merging changes.");
    [[self managedObjectContext]performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES];
}

正如我所说的,我有其他块被派往concurrentQueue进行更新和创建,使用非常相似的代码(在块的开头和结尾设置相同)并且它们工作正常。当删除被“处理”时,永远不会调用mergeChanges方法。

所有东西都是用dispatch_sync调用的,所以据说事情是在调用下一个块之前完成的。

我做错了什么?

由于

1 个答案:

答案 0 :(得分:3)

您需要致电-[NSManagedObjectContext save:]