Key data and topics

I am working on an application that uses basic data, and I know that this is not thread safe, but trying to figure out how to properly manage it. Let me explain what I still have ...

I created a singleton that initiates a managed object and then is accessible to all other classes, it works correctly, since the same address of a managed object is accepted by all classes.

Then I have two classes that execute in this order ...

  • Download data. This gets a record counter, and if the kernel database is zero loaded.
  • Tableview, which then displays the data stored in step 1.

My problem is that step 1. Always returns zero records and step 2. Works and returns the correct number of records.

Having done some testing of the problem with 1. This is because the thread works, if I send a request in the same thread that the managed object was created on it, it works fine.

So why is this in class 1. I have to make sure the request is in the correct stream, but in class 2. It just works, or is it just luck. Is there a recommended and documented approach to streams and master data?

thanks

+4
source share
1 answer

The golden rule for concurrency in Core Data: each NSManagedObjectContext should be accessible from only one thread - the thread that was created on . In addition, the managed entity can only be used with the MOC from which you took it - without passing it to other MOCs!

But you can share a persistent storage coordinator between threads, because each MOC blocks a PSC when it uses it, so a typical installation requires only one PSC for multiple MOCs.

More details here:

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

If your case 2. seems to work when using different threads, I would say that this is more for good luck and it does not work correctly. Do not depend on luck, follow the rule that I mentioned above, and everything will be fine.

Additional relevant reading:

What does it mean that 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 the API or documents say โ€œDo not do Xโ€, it doesnโ€™t mean that the execution of X will not succeed or every time it encounters problems - it just means that it may come to visit you again . Do not leave things aside, find out what you are allowed to do (API documents, etc.) And do it.

+11
source

All Articles