mkc842
mkc842

Reputation: 2381

why does NSManagedObjectContext Queue execute on main thread?

When I send a performBlock message to my MOC of type NSPrivateQueueConcurrencyType, like this:

[self.privateManagedObjectContext performBlockAndWait:^{
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"executing on the main thread!!");        
    }
    …
}];

I find that, by default, this executes on the main thread. The conditional in the above code triggers, and the Issue Navigator indicates that execution is occurring on Thread 1 in the NSManagedObject Queue.

This is very puzzling to me, because Apple tells us that "each thread must have its own entirely private managed object context." Given that an MOC of type NSMainQueueConcurrencyType will use the main thread, doesn't it violate thread confinement for an MOC of type NSPrivateQueueConcurrencyType to use the main thread?

Is the execution of my code on the main thread normal? Have I misunderstood thread confinement? I understand that a queue is not necessarily tied to a particular thread, but in this case it seems the private MOC queue should at a minimum avoid the main thread, if not have a single go-to thread. I'm having some weird bugs, so I need to figure out what's going on. Thanks!

Upvotes: 5

Views: 1188

Answers (1)

Martin R
Martin R

Reputation: 539745

This optimization is possible because performBlockAndWait: executes the block synchronously, i.e. the method does not return until the block has finished. Therefore the block will not be executed in parallel with other operations on the main thread.

(For the same reason, dispatch_sync(queue, ...) may execute a block on the main thread instead of a separate thread.)

Upvotes: 6

Related Questions