ioscore-datansorderedset

Inserting new Core Data object to to-many NSOrderedSet ignores index


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!


Solution

  • The issue lies in the initialization of entityBCopy, specifically with the newParent param. Initializing EntityB with a parent relationship, then immediately inserting the EntityB instance into the same parent is redundant. The Core Data generated insert method should handle setting the parent property on entityBCopy, assuming everything is set up correctly in the model.

    Therefore, removing the newParent parameter from the initializer should result in inserting at the correct index:

    // Inserting EntityB copy into EntityA 
    let entityBCopy = EntityB(entityB: entityBOriginal)
    entityA.insertIntoEntityBs(entityBCopy, at: index)
    

    Happy coding!