I'm getting a weird behaviour when inserting a new Core Data entity (EntityB) into the NSOrderedSet relationship property of another entity (EntityA); the index is ignored and the object is always inserted at the end of the ordered set.
The object being inserted is a copy of an existing object, using a different parent entity created using a custom copy initializer:
// EntityA
@NSManaged var entityBs: NSOrderedSet // to-many relationship
// EntityB
@NSManaged var entityA: EntityA?
// Inserting EntityB copy into EntityA
let entityBCopy = EntityB(entityB: entityBOriginal, newParent: entityA)
entityA.insertIntoEntityBs(entityBCopy, at: index)
entityBs before the insert:
entity0
entity1
entity2
entity3
entity4
entityBs after inserting newEntity2 at index 2:
entity0
entity1
entity2
entity3
entity4
newEntity2 < inserted at the end of ordered set, not at index 2
I've confirmed that index is within the bounds of entityBs' contents.
EntityA uses Core Data Generated Accessors, but I also tried inserting the object manually via the key value coding method - the same issue occurs. This makes me wonder if it's a problem on NSOrderedSet, rather than being a Core Data problem.
I have no ideas why this is happening, so any info would be welcome!
The issue lies in the initialization of
entityBCopy, specifically with thenewParentparam. InitializingEntityBwith a parent relationship, then immediately inserting theEntityBinstance into the same parent is redundant. The Core Data generatedinsertmethod should handle setting the parent property onentityBCopy, assuming everything is set up correctly in the model.Therefore, removing the
newParentparameter from the initializer should result in inserting at the correct index:Happy coding!