Search code examples
iosuitableviewcore-dataconcurrencynsmanagedobjectcontext

Applying Multi-Context CoreData to an NSOperationQueue-based app


I am still working upon my RSS Reader and though it finally achieves decent functionality, the UI Responsiveness appears to be very bad on an iPad 3.

In order to improve my app, I checked many source on the Internet and fell across this interesting gem where Marcus Zarra's approach (having a parent MOC dedicated to saving to the PSC in background) seduced me.

The example provided by Matthew Morey looks gorgeous but does only take a single operation into consideration: the mass-load of entries in an UITableView.

I tried to implement this solution into my app but it's obviously a mess. I have a MasterViewController which, when starting creates a serie of DBOperation objects which it sends to a serial (1 concurrent max) NSOperationQueue.

Each of my UIViewControllers also perform individual CoreData operations which they save individually (Mark a post as edit, a category as open or closed, etc.).

So, my questions are:

  • how (in a nutshell) should I implement a Multi-Contexted CoreData in my app?
  • Which controller should add which observer to get their respective UITableView reloaded?
  • which controller or delegate should perform the observe NSManagedObjectContextDidSaveNotification/mergechange operation?

I'm really confused by all of this and Markus Zarra's excellent book did help me too little, maybe because I took the wrong way from the very beginning...

Thanks in advance for your help


Solution

  • Marcus S. Zarra actually answers my questions in his excellent "Core Data 2nd Edition" book (if you buy only one Core-Data book this year, make it that one!) where he devotes a nice chapter to the concurrency.

    What I happened to ignore was how the child/parent relation works with MOCs.

    I just learned that a MOC declared with a parent MOC but no PSC will "push" its changes towards its parent whenever its save method is invoked.

    If our main thread MOC is himself the child of a private "writer" MOC using his own Private queue, then we can cascade the save which will be very fast in our main MOC (no disc involved), then delayed in the background in the private writer MOC, thus keeping the GUI responsive.

    I also learnt than whenever a MOC uses a private queue, he can only be accessed within a performBlock or performBlockAndWait block.

    Thanks a lot for your help, Leijonien, you desserved the upvotes!