问题
Currently I'm setting my NSManagedContext's by doing the following in ViewDidLoad:
.h
@property (nonatomic,strong) NSManagedObjectContext* managedObjectContext;
.m
viewDidLoad {
_managedObjectContext = [NSManagedObjectContext MR_contextForCurrentThread];
}
Question: Do I have to pass this same managed context to all of my subsequent viewcontrollers that I want to have access to this ManagedContexts, or can I write a new @property for each new viewcontroller's .h and then set each new viewcontrollers ManagedObject in .m with _managedObjectContext = [NSManagedObjectContext MR_contextForCurrentThread];
回答1:
When the Core Data stack is set up, MagicalRecord creates a default context of the "main queue concurrency type". If all your view controllers use this default context, you can
- (1) pass the context around from one view controller to the next,
- (2) call
[NSManagedObjectContext MR_defaultContext]in each view controller to get the default context,
and you could also, as you currently do
- (3) call
[NSManagedObjectContext MR_contextForCurrentThread]inviewDidLoadto get the default context.
But the last method works only because viewDidLoad is always called on the main thread and
MR_contextForCurrentThread returns the default context in that case.
However, MR_contextForCurrentThread creates additional contexts (of the private queue concurrency type) if called from a non-main
thread, and associates the context with a fixed NSThread. But, as @casademora correctly said, such a private queue context does not always use the same thread for each
operation. So MR_contextForCurrentThread should not be used on a non-main thread,
and it is identical to MR_defaultContext if called from the main thread.
Therefore, even if it works in your case, you should avoid method (3). Whether you choose method (1) or (2) is purely a matter of taste.
If you need an additional context, e.g. for background import operations, you can call
e.g. MR_context or MR_contextWithStoreCoordinator and pass that context to whereever
it is needed.
回答2:
Please stop using contextForCurrentThread. This goes doubly for using GCD queues. While GCD queues are implemented on top of the threading model, you are not guaranteed to get the same actual thread for every subsequent block.
If you need a new context, create a new private queue, main queue, or confinement context.
来源:https://stackoverflow.com/questions/17814656/passing-a-managedcontext-with-core-date-magical-record