ios - 只能使用-performBlock : on an NSManagedObjectContext that was created with a queue

标签 ios objective-c multithreading core-data grand-central-dispatch

我想在 Core Data 中使用多线程。我在 NSManageObject 中解析 xml 文件。我使用下面的代码,但出现运行时错误 Can only use -performBlock: on an NSManagedObjectContext that was created with a queue。怎么了?

//xmlParser

- (void)main
{
    dispatch_queue_t queueB = dispatch_queue_create("Create Books", NULL);
    dispatch_async(queueB, ^{
        // Opening xml
        // ...
        NSManagedObjectContext* context = [[NSManagedObjectContext alloc] init];
        [context setPersistentStoreCoordinator:mainContext].persistentStoreCoordinator];
        [context performBlock:^{
             // ...
             [self _parseNode:container_node appendTo:books inContext:context];
             // ...
             NSError* error = nil;
             [context save:&error];
             [mainContext performBlock:^{
                 NSError* parentError = nil;
                 [mainContext save:&parentError];
             }];
         }];
         [context release];
     });
     dispatch_release(queueB);
}

- (int)_parseNode:(axlNode*)inode appendTo:(NSMutableArray*)ioarray inContext:(NSManagedObjectContext*)context
{
    // ...
    [context executeFetchRequest:request error:&error];
    //...
}

最佳答案

performBlock 只能与 NSMainQueueConcurrencyType 的托管对象上下文 (MOC) 一起使用,或者 NSPrivateQueueConcurrencyType。在您的情况下,您应该使用

创建上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc]
                     initWithConcurrencyType:NSPrivateQueueConcurrencyType];

并且无需创建调度队列或使用 dispatch_async()。 MOC 创建和管理自己的队列, performBlock 确保 block 在 MOC 的队列上执行。

关于ios - 只能使用-performBlock : on an NSManagedObjectContext that was created with a queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17649985/

相关文章:

iOS - MailCore - 在 MCData.cc 崩溃 -appendBytes

ios - 在 iOS 7 中用于第三方调试的应用程序中显示日志语句的控制台

ios - UITableViewCell约束

java - 带有线程池的嵌套循环

java - 暂时提高多线程服务中的log4j2记录器级别

ios - 单元格或标题 View 高度的 UITableViewAutomaticDimension 导致 UITableView insertRowsAtIndexPaths() 崩溃

iphone - 如何访问 ios 邮件应用程序右上角使用的箭头按钮?

iphone - 核心数据 : Find the property of NSEntity Objects in NSMutableSet

ios - 如何使用系统字体调整操作表元素字体的大小?

multithreading - Spring Batch线程安全的ItemReader(过程指示器模式)