Search code examples
core-datansmanagedobjectcontextnsorderedset

NSOrderedSet in child NSManagedObjectContext loses order when saved


I have some NSManagedObjects with a one-to-many parent-child relationship where the "children" property is an NSOrderedSet.

When I create a new child, I do so in a child NSManagedObjectContext. I insert the child at the index 0 of the children set.

Before I save the child context I observe that the parent's children look like:

Parent

  • Kid1
  • Kid2
  • Kid3
  • Kid4(new)

But when I proceed to save the parent context I check the "updatedObjects" property and see that the parent's children are ordered incorrectly!

Parent

  • Kid1
  • Kid2
  • Kid3
  • Kid4(new)

NOTE: This only happens with newly created children. If the children already exist when I create the child context I am able to change their order on the child context and their positions in the ordered set are saved appropriately in the parent context.

I've tried messing with the merge policies of the parent and child contexts. Right now they are configured to the default error-policy and no errors are being thrown on save.


Solution

  • My main issue here was was related to cross-thread Core Data usage.

    I expected the symptoms of cross-thread misuse to be more obvious, but this is how they manifested for me. Making sure I was accessing managed object contexts correctly from all threads fixed my problems.