7

In my iOS application's interface I have explicit undo & redo button (shake-to-undo is a pretty heavyweight action and in this context, undos are performed pretty frequently). Normally, I would use KVO to observe NSUndoManager's canUndo and canRedo key paths and enable & disable the buttons as the notifications come in. Unfortunately, NSUndoManager doesn't seem to be KVO-compliant for those key paths -- or at least, I'm not seeing anything in terms of notifications.

So my question is: How do I get this working? Am I just doing it wrong with KVO? (I've double & triple checked but there's always that possibility). Is there another way to do this that I'm not thinking of? (I've though about just checking the value of -canUndo every time the runloop spins but that has kind of a bad code smell to me).

(Note that it's quite possible that NSUndoManager is different on the iOS and Mac OS X, so I don't think "It works on the Mac" is going to be a helpful answer, in this case)

Colin Barrett
  • 4,451
  • 1
  • 26
  • 33

1 Answers1

13

Register for your NSUndoManager's NSUndoManagerDidUndoChangeNotification and friends to examine when new undo groups are created and popped off the stack and update your button's states appropriately.

Jonathan.
  • 53,997
  • 54
  • 186
  • 290
Ashley Clark
  • 8,813
  • 3
  • 35
  • 35
  • 3
    Awesome -- NSUndoManagerWillCloseUndoGroupNotification is the one I had missed previously. Everything makes sense now. Thanks @aclark. – Colin Barrett Aug 14 '10 at 00:59
  • The documentation says: "Posted before an `NSUndoManager` object closes an undo group, which occurs in the implementation of the `endUndoGrouping` method. ". However, I can confirm that it gets posted when you register a single undo (e.g. with `-registerUndoWithTarget:selector:object:`). Very useful to call `canUndo` on `notification.object` (`NSUndoManager`) and enable/disable any "undo" button in the UI. – Nicolas Miari Nov 26 '15 at 09:14