Reputation: 32061
I have the following setup:
NSManagedObjectContext *parent = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSMainQueueConcurrencyType];
// other setup for parent
NSManagedObjectContext *child = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[child setParentContext:parent];
What I want is to save the parent whenever the child saves, so currently I do something like this:
[child performBlock^{
[child save:nil];
[parent performBlock:^{
[parent save:nil];
}
}];
That's me being safe, and calling save within the context's own queue. Is that necessary? Could I just do:
[child performBlock^{
[child save:nil];
[parent save:nil];
}];
Upvotes: 1
Views: 251
Reputation: 21144
You need to call the main context to save on its own queue and I assume that you use main queue for the parent context so you could do it like;
[child performBlock^{
[child save:nil];
[parent performSelectorOnMainThread:@selectorr(save:) withObject:nil waitUntilDone:NO];
}];
This code will make sure that your parent managedObjectContxt will always save in the main thread. And I think that it is a good idea to have main context always on the main thread which makes it easy to synchronise between different threads.
Upvotes: 1
Reputation: 539745
No, you cannot use the second variant. You would execute the save
operation for the parent context on the queue that is associated with the child context, instead of the main queue.
This means that the save
operation would be executed on a (potentially) different thread than the main thread, which is not allowed because managed object contexts are not thread safe.
See also Concurrency Support for Managed Object Contexts in the Core Data Release Notes for OS X v10.7 and iOS 5.0:
You use contexts using the queue-based concurrency types in conjunction with two new methods:
performBlock:
andperformBlockAndWait:
. ... 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:
andperformBlockAndWait:
ensure the block operations are executed on the queue specified for the context. ...
Upvotes: 2