Clearing the Undo Stack

If you are using undo managers in a reference-counted environment, you have to be careful about issues related to memory management. An NSUndoManager object does not retain the targets of undo operations. The client—the object performing undo operations—typically owns the undo manager, so if the undo manager in turn retained its target this would frequently create a retain cycle. This means, though, that an undo manager may potentially hold a reference to an object that has been deallocated. If a target object has been deallocated and an undo message is sent to it, this results in a runtime exception.

To guard against this, you must take care to clear undo operations for targets that are being deallocated. You typically do this in one of three ways, depending on the configuration of the client:

In a more general sense, it sometimes makes sense to clear all undo and redo operations. Some applications might want to do this when saving a document, for example. To this end, NSUndoManager defines the removeAllActions method, which clears both stacks.