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:
The client is the exclusive owner of the undo manager and the target of all undo operations.
In this case the client can simply release the undo manager in its
The client shares the undo manager with other clients.
To handle this the client should send
selfas the argument ) to the undo manager before releasing it in its
The client registers objects other than itself for undo operations.
Here either the client must watch for the other objects being deallocated in order to send
removeAllActionsWithTarget:, or the other objects must do so themselves when deallocated (which requires that they have a reference to the undo manager). This is likely to be needed with invocation-based undo.
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.
© 2011 Apple Inc. All Rights Reserved. (Last updated: 2011-06-03)