0
votes

I have a very peculiar.. issue happening with my NSFetchedResultsController.

My setup is using Magical Record, I have a child with the parent set as MR_defaultContext ([NSManagedObjectContext MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]]).

I create a nested context using the first view controller's managedObjectContext as the parent, use that for the next page, which is modal. This next page executes a fetch with a predicate, simple, finding all the entities in a to-many relationship.

Now, if I do not save the inserted entities prior to pushing to the next modal page, the fetch is correct. But.. if I save with [self.managedObjectContext MR_saveOnlySelfWithCompletion] and then push, the fetch is sometimes correct, sometimes (most times) random and incorrect. For example there are 5 entities it should be fetching, but it fetches 1, 3, 4, sometimes none. Very odd!

Even more odd is I keep the number of entities as a variable in the modal page, which shows 5 correctly. Always. And if I print out the parent entity of the to-many relationship, it does have all 5 relationships set (and the inverse is set correctly as well).

I have read about fetching the permanent IDS before saving, but that did not make a difference.

Anyone know what is going on?

2

2 Answers

0
votes

I guess that your issue might be caused by the fact that you are moving to the next modal page before MR_saveOnlySelfWithCompletion is done.

Try to push the next modal from within the completion block you pass to that method and everything should work.

0
votes

Ok, I was thinking about the child/parent relationship wrong. I watched the Core Data Best Practices from WWDC 2012, and sorted out what was going on.

I initially thought saving was necessary for the child to be able to access parent changes. Turns out that is not true - saving prior to the segue was unnecessary for the child context to access the changes on the parent context. So removing the save will have to do as it is not needed.

As an aside, I was using existingObjectWithID to get the object from the next modal page, which was unnecessary, as the changes from the parent context would be available to the child. I am not 100% sure why the object would not be fetched by this method as the documentation states If there is a managed object with the given ID already registered in the context, that object is returned directly which seems to me like it should be.

As another aside - saving the context from the child after pushing to modal (before the fetch) works just fine..

Still not really sure why the inconsistency with the fetch after the save from the parent VC.