How does NSUndoManager.groupsByEvent determine the current run loop pass?

237 views Asked by At

I'd like to understand/replicate the "group by run loop pass/cycle" feature of NSUndoManger:

NSUndoManager can group multiple calls to registerUndo() into a single "undo" operation when invoked multiple times on the same run loop cycle. This is determined by NSUndoManager.groupsByEvent, which is set to true by default.

So something like this:

// User clicks button... (causes a new run loop event)
undoManager.registerUndo(...) // #1
undoManager.registerUndo(...) // #2

...results in one undo group and clicking Edit → Undo reverts both changes at once.

Somehow NSUndoManager can figure out if two calls to registerUndo() are on the same run loop cycle. How does this work?

My use case:

I have code that sends property change notifications after the user interacts with the UI (e.g. clicks a button). There can be one or more events as the result of a user action. I'd like to group those and update the UI only once at the end of the current run loop.

1

There are 1 answers

2
Willeke On

NSUndoManager normally creates undo groups automatically during the run loop. The first time it is asked to record an undo operation in the run loop, it creates a new group. Then, at the end of the loop, it closes the group.

source: Undo Operations and Groups

NSUndoManager is part of the same framework as NSRunLoop so maybe NSRunLoop signals NSUndoManager to close a group. You don't know and you shouldn't want to know.