views:

961

answers:

2

In Apple's Core Data documentation for Multi-Threading with Core Data, they list the preferred method for thread safety as using a seperate NSManagedObjectContext per thread, with a shared NSPersistentStoreCoordinator.

If I have a number of NSOperations running one after the other on an NSOperationQueue, will there be a large overhead creating the context with each task?

With the NSOperationQueue having a max concurrent operation count of 1, many of my operations will be using the same thread. Can I use the thread dictionary to create one NSManagedObjectContext per thread? If I do so, will I have problems cleaning up my contexts later?

What’s the correct way to use Core Data in this instance?

A: 

Operations started using NSOperationQueue using a maximum concurrent operation count of 1 will not run all operations on the same thread. The operations will be executed one after the other, but a new thread will be created every time.

So creating objects in the thread dictionary will be of little use.

Philippe Leybaert
There's no guarantee that it will be a new thread every time. In fact, on Snow Leopard, NSOperationQueue uses Grand Central Dispatch which explicitly reuses threads.
BJ Homer
This question is about the iPhone, not about Snow Leopard. And of course there's no **guarantee**, is there ever?
Philippe Leybaert
+5  A: 

The correct way to use Core Data in this case is to create a separate NSManagedObjectContext per operation or to have a single context which you lock (via -[NSManagedObjectContext lock] before use and -[NSManagedObjectContext unlock] after use). The locked approach might make sense if the operations are serial and there are no other threads using the context.

Which approach to use is an empirical question that can't be asnwered without data. There are too many variables to have a general rule. Hard numbers from performance testing are the only way to make an informed decision.

Barry Wark