(CoreData) Using UndoManger on a private Managed Object Context

I am having trouble using UndoManager with a private Manged Object Context in CoreData. Here is my setup: I have my main context running on the main queue. I created a private context via let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) and connect it as a child context to my main context via privateContext.parent = mainContext. I also assigned an UndoManager to privateContext. This UndoManger has been set to use manual grouping via undoManager.groupsByEvent = false. So far so good.

Now to the part that gives me trouble: I want to change something on the private context and record this action for potential undoing. In order to do this a use a nested grouping structure (that is how it makes sense in my code). This is how i currently do this:

privateContext.performAndWait {
    undoManger.beginUndoGrouping
}
// do something in code unrelated to changes on the privateContext
privateContext.performAndWait {
    doChangesOnPrivateContext()
}
privateContext.performAndWait {
    undoManger.beginUndoGrouping
}
privateContext.performAndWait {
    doChangesOnPrivateContext()
}
privateContext.performAndWait {
    undoManger.endUndoGrouping
}
// do something in code unrelated to changes on the privateContext
privateContext.performAndWait {
    undoManger.endUndoGrouping
}

This leads to the error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '_setGroupIdentifier:: NSUndoManager is in invalid state, must begin a group before registering undo

which I had encountered before when beginUndoGrouping and endUndoGrouping were called from different threads. Further examination yields that this is also the case here as performAndWait runs the code on the private queue assigned to privateContext, but with the structure shown above beginUndoGrouping and endUndoGrouping are indeed called on different threads.

So here are my questions:

  • How do I do this correctly?
  • Do I misunderstand things and UndoMangager should not be used on a private context? If so, how would I setup things then?
(CoreData) Using UndoManger on a private Managed Object Context
 
 
Q