What does Apple mean when they say that a NSManagedObjectContext is owned by the thread or queue that created it?

后端 未结 2 1762
孤独总比滥情好
孤独总比滥情好 2020-12-02 04:20

It seems that in November, Apple updated both the NSManagedObjectContext Class Reference and the Core Data Programming Guide documents to explicitly bless serial GCD Dispatc

2条回答
  •  误落风尘
    2020-12-02 04:32

    Sounds like you had it right. If you're using threads, the thread that wants the context needs to create it. If you're using queues, the queue that wants the context should create it, most likely as the first block to execute on the queue. It sounds like the only confusing part is the bit about NSOperations. I think the confusion there is NSOperations don't provide any guarantee about what underlying thread/queue they run on, so it may not be safe to share a MOC between operations even if they all run on the same NSOperationQueue. An alternative explanation is that it's just confusing documentation.

    To sum it up:

    • If you're using threads, create the MOC on the thread that wants it
    • If you're using GCD, create the MOC in the very first block executed on your serial queue
    • If you're using NSOperation, create the MOC inside of the NSOperation and don't share it between operations. This may be a bit paranoid, but NSOperation doesn't guarantee what underlying thread/queue it runs on.

    Edit: According to bbum, the only real requirement is access needs to be serialized. This means that you can share a MOC across NSOperations as long as the operations are all added to the same queue, and the queue doesn't allow concurrent operations.

提交回复
热议问题