Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can only use -performBlock: on an NSManagedObjectContext that was created with a queue

I want to use multithreading with Core Data. I parse xml-file in NSManageObjects. I use the code below and I get runtime error Can only use -performBlock: on an NSManagedObjectContext that was created with a queue. What's wrong?

//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];
    //...
}
like image 614
Valentin Shamardin Avatar asked Jul 15 '13 08:07

Valentin Shamardin


1 Answers

performBlock can only be used with a managed object context (MOC) of the NSMainQueueConcurrencyType or NSPrivateQueueConcurrencyType. In your case, you should create the context with

NSManagedObjectContext *context = [[NSManagedObjectContext alloc]
                     initWithConcurrencyType:NSPrivateQueueConcurrencyType];

And there is no need to create a dispatch queue or use dispatch_async(). The MOC creates and manages its own queues, and performBlock ensures that the block is executed on the MOC's queue.

like image 155
Martin R Avatar answered Sep 19 '22 23:09

Martin R