I have an
NSManagedObject
with an NSOrderedSet
to-many relationship named 'children'. I am observing changes to this set using the following:addObserver(self, forKeyPath: #keyPath(children), options: [], context: nil)
This can be called only once in the initialisation of a lazy property on the
NSManagedObject
. Any new relations are added in a child NSManagedObjectContext
, and then saved down to my main context. When I set the relationship, I use the following code, only setting the 'many' side of the relationship from the 'one':superpoint.insertIntoChildren(self, at: 0)
insertIntoSubpointChildren
is an autogenerated accessor.In the child
NSManagedObjectContext
I see a single correct call to observeValue(forKeyPath...
, that gives me the correct insertion index on children
, when the above insertion code is called.However, when I save to the parent
NSManagedObjectContext
I am seeing two calls to observeValue(forKeyPath...
on the same object. The first call is for an insertion at the end of the NSOrderedSet
. The second call is for an insertion at the correct position.When evaluating the
NSOrderedSet
in each observation call, the new object is indeed at the position described - it is on the end of the set on the first call, and then moved to the correct position on the second call. However, I get no call to say that it was removed from the end position.I am not sure if I have set something up incorrectly here. The many objects in my one-many relationship will be unique, so I could write the code to work around this, but that feels wrong.
I have replicated this issue in a simple project here: Github: /GilesHammond/KVO-Core-Data-Extra/
Run in debug and select "ADD CHILD" multiple times from the app Main Menu. Observe the debug output showing the extra erroneous observation on the main NSManagedObjectContext.
Any thoughts on what I might be doing wrong?