Creating a NSManagedObjectContext on a private/background queue: how to do?

元气小坏坏 提交于 2019-12-08 07:42:55

问题


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:


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.



来源:https://stackoverflow.com/questions/23231781/creating-a-nsmanagedobjectcontext-on-a-private-background-queue-how-to-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!