Passing a ManagedContext with Core Date + Magical Record

后端 未结 2 1814
被撕碎了的回忆
被撕碎了的回忆 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.

提交回复
热议问题