【问题标题】:CoreData not processing deletes when performed on a background threadCoreData 在后台线程上执行时不处理删除
【发布时间】:2012-01-13 03:51:19
【问题描述】:

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

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

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 调用的,所以应该是在调用下一个块之前完成的。

我做错了什么?

谢谢

【问题讨论】:

  • 您何时保存要从中删除对象的 MOC?没有保存,没有NSManagedObjectContextDidSaveNotification

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


【解决方案1】:

您需要致电-[NSManagedObjectContext save:]

【讨论】:

  • 好笑。我只是用那句话来回答我自己的问题。哦!谢谢。
猜你喜欢
  • 2021-10-19
  • 2016-01-27
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多