Re: Core data fetch and multithreading
Re: Core data fetch and multithreading
- Subject: Re: Core data fetch and multithreading
- From: Chris Hanson <email@hidden>
- Date: Mon, 22 Nov 2010 22:40:58 -0800
On Nov 22, 2010, at 1:08 PM, Quincey Morris <email@hidden> wrote:
> On Nov 22, 2010, at 07:58, Hunter Hillegas wrote:
>
>> I think someone somewhere told me that if you create a MOC on the main thread, there's some special runloop integration that is included, hence one of the reasons it's important to not create one on the main thread and then pass it around.
>
> Perhaps that's true, but it sounds like an urban myth. If it's true, the MOC locking approach can't work *at all* either -- because for the duration of the lock the MOC is in fact being used on a background thread. But the MOC locking approach *can* work, ergo ... etc ... QED.
You're right that context locking between a main-thread and non-main-thread use of a single context can't work; this isn't an "urban myth." Context locking can only really work for contexts created on background threads, but you shouldn't need context locking anyway; just use one context per thread/queue and share the coordinator instead. Life will be much easier.
> It seems feasible to design your app so that when something non-UI-related needs to happen, you can dispatch the work as a GCD-based operation.
All NSOperations are "GCD operations." I generally recommend not using raw GCD in Cocoa code, instead preferring the higher level abstraction offered by NSOperation (which supports dependencies, priorities, cancellation, and so on). Using GCD doesn't even really get you much in terms of lines-of-code savings, especially once you start subclassing NSOperation and building your own abstractions atop it.
> For operations that need to modify the data, it's easy to just pass the main MOC as a parameter into the GCD block, isn't it?
Don't do this; it isn't safe to just pass a main-thread context to a background thread. Instead, pass the persistent store coordinator and the IDs of any needed managed objects, and create a managed object context within your operation with. Contexts are cheap, you can use them as scratch pads like this.
-- Chris
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden