Question

I'm running into some trouble working with CoreData in a multithreaded app using NSOperations. I am using nested ManagedObjectContexts through MagicalRecord (2.0.3) as follows:

Root Context (saves to disk)
|
Main Thread Context (for populating the UI)
|
Sub-Context(s) (used to add/edit/remove data)

I have a single NSOperationQueue to handle all data processing.

For the most part, things work right, I can asynchronously download data, then feed it to an NSOperation which then writes it to one of the sub-contexts. Saving at the end of the operation pushes the changes to the main context and the UI updates. Great!

The problem is that if a sub-context deletes an entity and saves (pushing it to the main context), a sibling sub-context will still think that it exists. So then if a sibling tries to fault the entity and pull it from it's parent (the main context) I get a crash.

I have 2 questions:

  • Should I use MOC notifications to merge the changes pushed to the main MOC back to it's other children? I this and was getting another crash...
  • Should I even have mutltiple sub-contexts? MOC's are supposed to be associated with a single thread (MagicalRecord helps automate this for me), and I have a single NSOperationQueue for saving data, so shouldn't I only have 1 sub-context? I've verified that sometimes my saves are performed by different contexts.

I'd appreciate any advice. Thanks.

Was it helpful?

Solution

You can, and should, have multiple sub contexts. However, I'm not sure if the classic "thread isolation mode" of contexts is the model you should have anymore. That is what you're doing when you say that a context should belong to a particular thread. MagicalRecord 2.0x uses private queue contexts now, and as such will behave a tad differently. There are no rules saying that sibling contexts need to stay in sync. You'd have to do that yourself. A very simple solution would be to listen to "did save" notifications on the context you're saving, and either reset, or create a new context on the other thread. You can do this with notifications, or a completion black that MagicalRecord provides.

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top