NSUndoManager

We all make mistakes. Thankfully, Foundation comes to our rescue for more than just our misspellings. Cocoa includes a simple yet robust API for undoing or redoing actions through NSUndoManager.

nshipster.com/nsundomanager/

NSUndoManager gives you full undo/redo with almost no code. While you change something, tell the undo manager how to reverse it. Undoing the undo automatically becomes redo.

Two ways to register an undo:

Always set a localised action name: undoManager?.setActionName("Move")

Group related actions: beginUndoGrouping()endUndoGrouping()

Clear the stack when the context changes: undoManager?.removeAllActions()

For opposite actions (add/remove, show/hide) check undoManager?.isUndoing before naming so the menu says “Undo Add” / “Redo Add” correctly. On iOS, make your view controller first responder (canBecomeFirstResponder = true, call becomeFirstResponder() in viewDidAppear, resignFirstResponder() in viewWillDisappear). The system shows the standard shake-to-undo dialog automatically.

NSUndoManager is one of the highest-value APIs in Cocoa, a few lines give unlimited undo/redo, proper menu titles, and shake-to-undo for free. Use it everywhere it makes sense.


Category:

Year: