Passing a ManagedContext with Core Date + Magical Record

后端 未结 2 1804
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 14:16

Currently I\'m setting my NSManagedContext\'s by doing the following in ViewDidLoad:

.h

@property (nonatomic,strong) NSManagedObject         


        
相关标签:
2条回答
  • 2021-01-15 14:46

    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] in viewDidLoad to 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.

    0 讨论(0)
  • 2021-01-15 15:10

    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.

    0 讨论(0)
提交回复
热议问题