Creating a NSManagedObjectContext on a private/bac

2019-05-31 07:01发布

I am confused about how to create a MOC on other threads than the main thread.

On one hand, in the doc, one can read

A consequence of this is that a context assumes the default owner is the thread or queue that allocated it—this is determined by the thread that calls its init method. You should not, therefore, initialize a context on one thread then pass it to a different thread.

But on the other hand, I have seen code where an auxiliary MOC is created the following way, on the main thread:

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

    [parentContext performBlockAndWait:^{
        [parentContext setUndoManager:nil]; // no point in it supporting undo
        [parentContext setPersistentStoreCoordinator:coordinator];
    }];

So, what is the good way to create an auxiliary MOC? Maybe I should precise that this auxiliary MOC is a @property of a central class of the project (AppDelegate for example).

1条回答
Evening l夕情丶
2楼-- · 2019-05-31 07:50

The docs are ambiguous at best.

In my testing, you do not need to use a queue to attach the NSManagedObjectContext to its parent or the NSPersistentStoreCoordinator.

If you are doing a NSConfinmentConcurrencyType I set the parent or coordinator on the thread that created it (since that is the thread that can use it).

If you are doing a NSPrivateQueueConcurrencyType I set the parent or coordinator on the thread that created it as well. It is the usage of the NSManagedObjectContext that is confined or restricted to the private queue. I define the usage as executing a fetch, deleting an object, etc. Configuring the NSManagedObjectContext is not restricted.

This of course is not in the documentation but the results were produced through testing back when accessing a NSManagedObjectContext incorrectly caused an exception.

查看更多
登录 后发表回答