Skip navigation.
 
mlRe: How to use CoreData with multiple threads and ManagedObjectContexts
FROM : Chris Hanson
DATE : Sun Nov 27 08:03:52 2005

On Nov 26, 2005, at 10:45 PM, Matt Ronge wrote:

> I read that it's suggested that each thread have it's own 
> NSManagedObjectContext. So if each of my threads has their own 
> NSManagedObjectContext, and I update one ManagedObjectContext, will 
> the ManagedObjectContext in the other thread be magically updated 
> as well? To make things more clear, if my worker thread updates 
> it's NSManagedObjectContext will the NSManagedObjectContext which 
> the bindings are attached to change as well? I'm guessing no, since 
> that seems too easy?


It's not because it would be too easy; it's because that such change-
propagation is only sometimes what you want, and can have serious 
performance and data-consistency implications.  (Imagine changing an 
object in one context and attempting to propagate the change to a 
couple other contexts where you're getting ready to change the 
object, or where you have just changed it and are in the process of 
saving it.)  Managed object contexts are relatively independent 
scratchpads for your data

See /Developer/Examples/CoreData/BackgroundFetching for an example of 
how to work with multiple contexts in multiple threads, and how to do 
change propagation yourself.  The short summary is to use an SQLite 
persistent store, save the context where you make the changes, send 
the object IDs for changed objects to your other thread, and have the 
other thread refresh its objects with those IDs.

> Or should I share the same NSManagedObjectContext and do a trylock 
> on it before either thread accesses it?


This won't do what you want or expect.  More specifically, this 
general pattern -- "I need to access a resource in multiple threads, 
so I'll just put a lock around it" -- will only work if you control 
*every* point of access to that resource and can make them all use 
your lock.  As you say in your post, you have interface elements 
bound to these objects.  This means that there is a point of access 
to the object that is outside your control; Cocoa bindings aren't 
thread-safe, and there are no hooks that you can use to make them 
lock on your context.

Your best bet is to follow the BackgroundFetching example.

  -- Chris

Related mailsAuthorDate
mlHow to use CoreData with multiple threads and ManagedObjectContexts Matt Ronge Nov 27, 07:45
mlRe: How to use CoreData with multiple threads and ManagedObjectContexts Chris Hanson Nov 27, 08:03
mlRe: How to use CoreData with multiple threads and ManagedObjectContexts Matt Ronge Nov 27, 08:19
mlRe: How to use CoreData with multiple threads and ManagedObjectContexts Peter Sampson Nov 27, 08:27
mlRe: How to use CoreData with multiple threads and ManagedObjectContexts Shawn Erickson Nov 27, 18:47