Search code examples
core-datansmanagedobjectnsmanagedobjectcontextnsfetchrequest

Core Data fetching... Why doesn't Managed Object get fetched using context B after inserting it in context A and saving context A?


I am not sure what I'm missing here so I'll try to explain a problem I'm having.

I have two nsmanagedobjectcontexts. I will call them A and B.

  1. I insert a new entity E in A
  2. I save A
  3. from B I try to fetch all the E entities found in store with a simple fetchRequest
  4. When executing the NSFetchRequest to get all E entities from B I cannot get the one I inserted in A even though A was saved.
  5. I can get E if I execute the NSFetchRequest against A.

I thought that once I save a context the ManagedObject in that context would get saved to the persistent store (I only have one persistent store setup). So then I thought that I could get the managed object E from what ever context I wanted since any NSFetchedRequest fetches from the persistent store into the context I'm executing it on.

What am I missing here? Why can't I get E from any context I want after saving context A in which E was inserted in in the first place?


Solution

  • You need to merge the changes from context A in to context B. or instantiate context B after the save of context A.

    Take a look at the documentation for mergeChangesFromContextDidSaveNotification on NSManagedObjectContext.