magicalpanda / MagicalRecord

Super Awesome Easy Fetching for Core Data!
Other
10.8k stars 1.79k forks source link

Why [NSManagedObjectContext MR_context] has defaultContext as parent context ? #1111

Closed kenmaz closed 8 years ago

kenmaz commented 8 years ago

I aften see example code to fetch an object in background. Like a following.

let context = NSManagedObjectContext.MR_context
context.performBlock {
    let person = Person.MR_find(..., context:context)
    ....
}

But, I think this code is not recommended. Because MagicalRecord's MR_context creates local context with MR_defaultContext as parent context. MR_defaultContext is NSMainQueueConcurrencyType context. it works on main thread.

So the above code run through the main thread when fetch some data. It cause a little blocking in main thread. It is not good for fetching performance.

I think the following code is good.

let rootContext = NSManagedObjectContext.MR_rootSavingContext
let context = NSManagedObjectContext.MR_contextWithParent(rootContext)
context.performBlock {
    let person = Person.MR_find(..., context:context)
    ....
}

Because this code doesn't run in main thread. Both MR_rootSavingContext and local context are NSPrivateQueueConcurrencyType. It run in background perfectly.

Moreover , if some object is changed in main thread, Maybe the first code is affected that changes accidentally.

The first code's pattern is very elegant but not good performance and un-safe. So I think MR_context should use MR_rootSavingContext as parent context like the second code.

Is my idea good or bad ?

Thanks.

Alydyn commented 8 years ago

[NSManagedObjectContext MR_context] creates a new NSManagedObjectContext with MR_rootSavingContext as it's parent, not MR_defaultContext as the parent.

kenmaz commented 8 years ago

Oh..Sorry, my working copy was version 2.2. it's old version. Actually, it was fixed already in version 2.3.

https://github.com/magicalpanda/MagicalRecord/commit/75538201c80517f47e0b9dba01a1a70fdc0c9df2#diff-163cfa5fafafdc18bd47237691e22805L177

Thanks you for helping me.