Reputation: 26223
Simple question really, my Core Data UIManagedDocument is created on the main thread, what I want to know is when I call performBlock does that block queue/run on the main thread (the same thread where the Managed Document was created)?
dispatch_queue_t backgroundQueue = dispatch_queue_create("DownloadQueue", NULL);
dispatch_async(backgroundQueue, ^{
// Get data from web
[document.managedObjectContext performBlock:^{
// Add data to Core Data
}];
});
Upvotes: 4
Views: 1453
Reputation: 26223
When using UIManagedDocument
the managedObjectContext is created (just like it was prior to OS X v10.7 and iOS 5) using what equates to the default Confinement type NSConfinementConcurrencyType
. Simply put, this concurrency type specifies that the context will not be used on any other thread other than the one that originally created the context.
In this case the UIManagedDocument
(and its context) were created on the main thread, messaging performBlock:
will execute the associated block back on the main thread. By using performBlock:
you don't actually have to know on which thread the managedObjectContext was created, messaging performBlock:
will always execute its associated block on the same thread the context resides on.
Upvotes: 0
Reputation: 871
You may read the apple release notes: CoreData Release Notes for iOS5
You can use contexts using the confinement pattern just as you have prior to OS X v10.7 and iOS 5. You send the contexts messages directly; it’s up to you to ensure that you send the messages from the right queue.
You use contexts using the queue-based concurrency types in conjunction with two new methods: performBlock: and performBlockAndWait:. You group “standard” messages to send to the context (including initialization such as setting the persistent store coordinator and so on) within a block to pass to one of these methods. The one exception is: if your code is executing on the main thread, you can invoke methods on the main queue style contexts directly instead of using the block based API.
performBlock: and performBlockAndWait: ensure the block operations are executed on the queue specified for the context. The performBlock: method returns immediately and the context executes the block methods on its own thread. With the performBlockAndWait: method, the context still executes the block methods on its own thread, but the method doesn’t return until the block is executed.
It’s important to appreciate that blocks are executed as a distinct body of work. As soon as your block ends, anyone else can enqueue another block, undo changes, reset the context, and so on. Thus blocks may be quite large, and typically end by invoking save:.
Upvotes: 2