views:

703

answers:

2

Hi all,

I'm trying to use core data in a multi thread way. I simply want to show the application with the previously downloaded data while downloading new data in background. This should let the user access the application during update process.

I have a NSURLConnection which download the file asyncronously using delegate (and showing the progress), then i use an XMLParser to parse the new data and create new NSManagedObjects in a separate context, with its own persistentStore and using a separate thread.

The problem is that creating new objects in the same context of the old one while showing it can throws BAD_INSTRUCTION exception. So, I decided to use a separate context for the new data, but I can't figure out a way to move all the objects to the other context once finished.

Paolo aka SlowTree

+6  A: 

This Apple document is the place to start. Read it really carefully... I was bitten many times by my misunderstandings!

Basic rules are:

  1. Use one NSPersistentStoreCoordinator per program. You don't need them per thread.
  2. Create one NSManagedObjectContext per thread.
  3. Never pass an NSManagedObject on a thread to the other thread.
  4. Instead, get the object IDs via -objectID and pass it to the other thread.

More rules:

  1. Make sure you save the object into the store before getting the object ID. Until saved, they're temporary, and you can't access them from another thread.
  2. And beware of the merge policies if you make changes to the managed objects from more than one thread.
  3. NSManagedObjectContext's -mergeChangesFromContextDidSaveNotification: is helpful.

But let me repeat, please read the document carefully! It's really worth it!

Yuji
I found a great example of merging contexts in CoreDataBooks (mergeChangesFromContextDidSaveNotification). Thank you very much. Have a nice day.Paolo aka SlowTree
SlowTree
Oh thank god. I reading this has solved my issues.Was importing a large set of data in a background thread and getting a multitude of unpredictable exceptions.Instantiating the context in the background thread rather than passing it though seems to have fixed my isses.
half_brick
A: 

I hope this can help all the peoples that meet problems using core data in a multithread environment.

Take a look at "Top Songs 2" in apple documentation. With this code i took the "red pill" of Matrix, and discovered a new world, without double free error, and without faults. :D

Hope this helps.

Paolo

p.s. Many thanks to Yuji, in the documentation you described above I found that example.

SlowTree