In iOS5, I have a NSManagedObjectContext which I create with a NSPrivateQueueConcurrencyType, like so:
self.moc = [[[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType] autorelease];
moc.parentContext = rootContext;
This executes on the main thread, but if I understand the doc correctly that shouldn’t matter, since the MOC gets its own queue, right?
Now, at some point I perform a fetch request, like so:
[self.moc performBlockAndWait:^() { // (1)
NSError* err = nil;
result = [self.moc executeFetchRequest:request error:&err];
NSLog(@"%@ %@", [NSThread currentThread], [NSThread isMainThread]?@"MAIN":@"");
}];
The invocation (1) is also called on the main thread. But I expect the fetch request inside the block to execute on the private MOC thread. Correct so far?
However, if I check the current thread inside the block, it actually is the main thread! The NSLog prints:
<NSThread: 0x6b10780>{name = (null), num = 1} MAIN
Checking the thread dump confirms this.
The fetch should NOT be executed on the main thread, because this does occasionally result in a deadlock with some other running code. So what am I doing wrong here?
Ok, I’m still not entirely sure about the mechanics here, i.e. how something posted on the context-private queue ends up on the main thread. I suspect it has to do with the performBlockAndWait, which executes the block synchronously. I have rewritten stuff so everything is now done asynchronously, and the block is now executed on its private thread.
Thanks for all suggestions.