Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data & Threads

I'm working on an app that uses core data and I'm aware that this is not thread safe but struggling to understand how to manage this correctly. Let me explain what I have so far...

I've created a singleton the initiates the managed object and is then available to all other classes, this appears to be working correctly as the same managed object address is received by all classes.

I then have two clases that are executed in this order...

  1. Data load. This gets the record count and if zero loads the core data base.
  2. Tableview that then displays the data stored in step 1.

My problem is that step 1. Is always returning zero records, and step 2. Is working and returns the correct record count.

Having done some testing the problem with 1. Is due to the thread its running on, if I despatch the request on the same thread that the managed object was created on it works perfectly.

So why is it in class 1. i have to ensure that the request is on the correct thread but in class 2. It just works, or is it just pure luck. Is there a recommended and documented approach to threads and core data?

Thanks

like image 337
Duncan Hill Avatar asked Dec 21 '22 10:12

Duncan Hill


1 Answers

The golden rule for concurrency in Core Data is: each NSManagedObjectContext must only be accessed from one thread - the thread it was created on. Also, a managed object can only be used with the MOC you fetched it with - no passing it to other MOCs!

But you can share a persistent store coordinator between threads because each MOC locks the PSC when it uses it - so a common setup is just to have one PSC for multiple MOCs.

More info here:

http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdConcurrency.html

If your case 2. seems to be working when using different threads, I'd say it's more down to luck, and it doesn't make it the right thing to do. Don't depend on luck, follow the rule I mentioned above and all will be good.

Additional relevant reading:

What is meant by CoreData is not thread safe?

http://www.cocoanetics.com/2012/07/multi-context-coredata/

http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache/

http://digitalflapjack.com/blog/2010/jun/11/parallelcoredata/

http://www.duckrowing.com/2010/03/11/using-core-data-on-multiple-threads/

As a general rule, it's worth remembering that when APIs or docs say "Don't do X", it doesn't mean that doing X will fail or run into problems every time -- it just means that it will probably come back to haunt you one day. Don't leave things to chance, find out what you're allowed to do (API docs etc.) and do that.

like image 154
occulus Avatar answered Jan 05 '23 18:01

occulus