Program development We often use the two shortcuts CTRL + Z and CTRL + C, undo and copy, Cocoa development can also achieve these two operations, provide us with a very simple operation class Nsundomanger, also can be called the revocation Manager, Nsundomanger internally maintains two stacks, the undo stack and the redo stack. Creating a revocable operation requires creating a reverse operation and then making the corresponding change by reversing the operation, which is very simple to implement.
First, let's look at a very simple example:
Message *msg=[[message Alloc]init]; [MSG addobjectmethod:@ "Flyelephant"]; [MSG addobjectmethod:@ "http://www.cnblogs.com/xiaofeixiang/"]; NSLog (@ "%@", Msg.mutablearr); [Msg.undomanger undo];//Cancel NSLog (@ "%@", Msg.mutablearr); [Msg.undomanger redo];//Redo NSLog (@ "%@", Msg.mutablearr);
The variable group attribute in the message class Mutalearr, first look at the results, you can think about how it is implemented:
The array initialization element is init, then we add two new elements, this time by undo to cancel the newly added elements, and then we will remove the elements by redo into the array again;
-(void) Addobjectmethod: (NSString *) str{ [[Self.undomanger preparewithinvocationtarget:self] removeobjectmethod:str];//reverse Removal [Self.mutablearr addobject:str];} -(void) Removeobjectmethod: (NSString *) str{ [[Self.undomanger preparewithinvocationtarget:self] addobjectmethod:str];//Reverse Add if ([Self.mutablearr containsobject:str]) { [Self.mutablearr removeobject:str] ; }}
If careful will find that we in two corresponding methods are added to the corresponding reverse operation, if you only need to cancel, then in the Removeobjectmethod method, do not need to reverse operation, of course, the use of Redo method can not be executed, depending on the needs;
There are three ways to undo a manager record:
-(ID) Preparewithinvocationtarget: (ID) target;-(void) Registerundowithtarget: (ID) Target selector: (SEL) Selector Object: (Nullable ID) anobject;-(void) Registerundowithtarget: (ID) Target handler: (void (^) (id target)) undohandler Ns_ AVAILABLE (10_11, 9_0) Ns_refined_for_swift;
Preparewithinvocationtarget is what we use, of course you can pass Registerundowithtarget: (ID) Target selector: (SEL) Selector object: ( Nullable ID) anobject to use , Registerundowithtarget:hanlder Pass the change in the form of block, but it needs to be used in iOS9, to avoid creating a retaining ring when used.
iOS Development-nsundomanager undo (undo) and Redo (redo)