Kodeco Forums

Video Tutorial: Intermediate Core Data Part 5: Managed Object Contexts

Learn how to set up multiple managed object contexts in a parent child relationship.

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3815-intermediate-core-data/lessons/6

Thanks for the amazing tutorial Greg. I have a question about saving the .MainQueueConcurrencyType Managed Object context ( MOC)

Why can’t we use performBlock() for saving the MainQueue MOC? I remember you mentioning in the video, “Because this is a MainQueue MOC we have to use performBlockAndWait”. Could you please elaborate on why?

Also I have a scenario where most of the CoreData operations need to happen in background, but all the fetch operations need to happen in ForeGround.
My MOC layout for this problem is,

In order to ensure that fetch operations can be done on the .MainQueue MOC and also retain the performance gain explained the video, I have decided to go with Private MOC grandparent ← MainQueue MOC parent ← PrivateQueue MOC child. This way all the background core data operations can happen on privateQueue MOC child, a save() on MOC child will ensure that MainQueueMOC is the “Single Point of Truth”. Also, hitting MainQueue MOC.save() in performBlockAndWait will be instantaneous and the grandparent Private MOC . save() can be done asynchronously when it actually saves to the persistent store.

Is this a good MOC relationship architecture for my scenario? I have also read in the NSManagedObjectContext documentation that we can have 2 child MOC to a single parent MOC and the 2 children can keep track of changes in other MOC using some notifications. After listening to video tutorials, I am not sure when 2 sibling MOC scenario would be useful.

Sorry for the long post, but would really appreciate your thoughts.

Hi @shruti, I might have been a little too hand-wavy with the words “have to”. What I meant was that since you generally don’t want to block the main thread, you probably want performBlockAndWait. You can of course use regular performBlock on main queue contexts, with the knowledge that this will run synchronously.

I usually think of child contexts as “scratchpads” for a particular use: for example, adding a record or updating a record. Almost like a database transaction, so if you decide you don’t like the changes you can just throw away the child context and nothing actually bubbled up to the parent.

That’s a pretty simple use case though — you have to decide what’s best for your own apps!

1 Like

Hi Greg, Thanks for the awesome tutorials. I need a help from you.

When I am fetching the images from core data and setting it to the table view image. I find some lag while I am scrolling the table view. Can you please help me to solve this problem.

Thank you for taking the time to considering my request.