Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producer Consumer Issue with Core Data

I've a Core Data application. In the producer thread, I pull data from a web service and store it in my object and call save. My consumer object is a table view controller that displays the same. However, the app crashes and I get NSFetchedResultsController Error: expected to find object (entity: FeedEntry; id: 0xf46f40 ; data: ) in section (null) for deletion

on the console. When I debug it, everything works fine. So I understood that it's like a race issue.

How is these kind of problem solved? What's the best way to design a producer-consumer app with core-data?

like image 712
Mugunth Avatar asked May 23 '09 19:05

Mugunth


1 Answers

If you are targeting Leopard or later, Apple has made things a touch easier.

In your producer thread create a MOC with the same PSC as the MOC in your main thread. You can pull objects from your webservice in this thread, create the new objects, and save them as normal.

In your consumer thread, add your controller as an observer for the NSManagedObjectContextDidSaveNotification. Your callback should look something like:

- (void) managedObjectContextDidSave:(NSNotification *)notification
{
  NSManagedObjectContext *managedObjectContext = [notification object];
  if(managedObjectContext != self.managedObjectContext)
    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

In this way, objects saved in the producer thread will be automatically pulled in your consumer thread.

like image 75
sbooth Avatar answered Oct 07 '22 09:10

sbooth