views:

461

answers:

2

I have a core data application based on the default xcode template, I have the main UI which is used for viewing the data and then I have a background thread which is downloading/inserting/editing data.

I figured when the application launches I can create two NSManagedObjectContext, one which the applications reads from and the other in the background thread will be written to, then when it has finished writing it will call performSelectorOnMainThread to sync the two NSManagedObjectContext objects.

I am fairly new to cocoa and wondered if anyone could confirm that this should work and does anyone know of an example or discussion about this as I cannot get the syncing to work correctly.

+1  A: 

Are you manually creating the background thread? If you are, I would recommend following Cocoa's delegate pattern in NSURLConnection to do the actual downloading in the background and the processing of the data in the foreground.

If you feel you still need manually created threads, read the Multi-Threading in Core Data section of the Core Data Programming Guide for more insight.

Martin Gordon
Thanks for responding, I am creating threads manually as I need to download data, process it, download more data depending on conditions and then insert the data into core data, all while the user is browsing the data already stored. I have read that apple doc but I missed the bit about having two persistent store coordinators, I will give it another shot.
Craig
I created a separate managed object context for each thread and share a single persistent store coordinator as apple suggest however I can't get it to reload or merge the data in the main managed object once the background thread has finished running, I would think there must be an easy way to tell it to reload in the main thread however I can't seem to find it.
Craig
You can call a method on the main thread by using the NSObject method called -performSelectorOnMainThread:withObject:waitUntilDone: Again, I would recommend using NSURLConnection's asynchronous methods rather than doing it synchronously over your own threads.
Martin Gordon
+2  A: 

You want to take a look at -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:]. Register for change notifications from your worker thread's managed object context. In the notification callback, call your main thread's managed object context's mergeChangesFromContextDidSaveNotification. Be sure you invoke this method on the main thread (the change notification will be posted on the work thread).

Barry Wark