Undo Group with Core Data across spins of run loop

424 views Asked by At

I'm trying to setup an undo group that spans the entirety of changes that occur during a pan gesture recognizer. The objects being modified are NSManagedObjects from Core Data.

When the gesture enters the "began" phase, the code starts an undo group and turns off grouping by event. On "end" and "cancel" phases, the group is ended and grouping by event is turned back on.

On every "change" of the recognizer, the same core data object is updated. Subsequently, Core Data creates a new undo group for that specific change.

Is there any way I can get core data to stop that? Or do I need to change how undo is being handled in this case?

I have a sample project here that has the relevant code in BBQMainViewController.m's handlePanGesture: method (line 82). The project prints to the console the undo stack on every update of the recognizer. As you can see, the undo stack builds and builds. If you comment out line 168, the undo stack does not build up.

2

There are 2 answers

0
Patrick Burleson On BEST ANSWER

It turns out the issue I was seeing was actually caused by the app I'm working on not updating the UI correctly post undo.

Creating an undo group when the gesture starts and then closing it in the end or cancelled states wraps all the undo groups core data creates during the recogizer's change state updates. A call to undo on the undo manager undoes the entire group including the nested groups created by Core Data.

In short: user error. As usual.

1
gschandler On

Since you are modifying the same NSManagedObject every time through the gesture recognizer cycle (well, in the final else clause anyhow), why not cache the value and set the object's value just the once at UIGestureRecognizerStateEnded?

It may be (and I am not yet enough of a Core Data expert to know for sure) that Core Data is explicitly creating a new undo group level for every change (at least to same object in the graph) regardless of your setGroupsByEvent: settings.