How to implement undo using NSUndoManager?

只愿长相守 提交于 2019-12-11 09:13:44

问题


I am trying to add an NSUndoManager to my program but I am not sure how to register the methods with the manager? using :

[myUndoManager registerUndoWithTarget:selector:object:];

what if I have the following method:

-(IBAction)tapButton:(id)sender {
   myFoo++;    
   yourFoo++;    //incrementing integers
   fooFoo++;
}

How can I register this method with the undo manager? The object of the selector (sender) is not what I want to register. I need to decrement myFoo, yourFoo, and fooFoo with a single undo call.


回答1:


Write another method -(void) decrementIntegers and register that like this:

[undoManager registerUndoWithTarget: self selector: @selector( decrementIntegers ) object: nil];

In this method you need to register your original method again to provide redo:

[undoManager registerUndoWithTarget: self selector: @selector( tapButton: ) object: self];

But a better way to do this would be to use accessors for your integers and do undo registering in there. Something like this:

- (void) setMyFoo: (int) newMyFoo;
{
   if (myFoo != newMyFoo) {
      [[undoManager prepareWithInvocationTarget: self] setMyFoo: myFoo];
      myFoo = newMyFoo;
   }
}


来源:https://stackoverflow.com/questions/3616946/how-to-implement-undo-using-nsundomanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!