It is convenient to use Nsundomanager in cocoa to complete the undo operation. The Nsundomanager records the messages that modify and revoke the operation. This mechanism uses a stack of two Nsinvocation objects.
Nsinvocation will wrap the message (selector and receiver and parameters) into an object, which is an instance of nsinvocation. When an object receives a message that it does not understand, the message sending mechanism checks whether the object implements the Forwardinvocation method before reporting an error. If implemented, the message is packaged into a Nsinvocation object, and then the Forwardinvocation method is called.
1) Nsundomanager Working principle
When the operation is performed, the controller adds a invocation to the undo stack of the action's inverse operation. When the undo operation is performed, the inverse of the undo operation is added to the redo stack in such a way that the undo and redo two stacks cleverly implement the undo operation.
It is important to note that the Nsinvocation instances are stored in the stack.
2) Example
Assuming that there is walkleft in our program and the inverse method of this method Walkright, we can implement the Undo function in this way.
-(void) Walkleft
{
Position = position + 10;
[[UndoManager preparewithinvocationtarget:self] walkright];
[Self showthechangestothepostion];
}
Preparewithinvocationtarget: The method records the target and returns UndoManager, and then UndoManager overloads the Forwardinvocation method, The invocation of the Walkright method is added to the undo stack.
-(void) walkright
{
Position = position-10;
[[UndoManager preparewithinvocationtarget:self] walkleft];
[Self showthechangestothepostion];
}
UndoManager can also set the name of the Undo menu action:
[UndoManager setactionname:@ "Insert"];
Related Demo
iOS Development Cocoa Programming--nsundomanager