NSUndoManager的一点学习记录

这两天看了一个coredata的官方代码,发现了里面的NSUndoManager类,就稍微的研究了一下.下面是我的一点学习记录

NSUndoManager 说白了主要就是2个方法,一个是redo,一个是undo,也就是对程序的撤销和恢复



-(void)undo
{
    [self.undoManage undo];
}
-(void)redo
{
    [self.undoManage redo];
}

它里面有一个
prepareWithInvocationTarget方法需要注意, 当进行操作时,控制器会添加一个该操作的逆操作的invocation到Undo栈中。当进行Undo操作时,Undo操作的逆操作会倍添加到Redo栈中,就这样利用Undo和Redo两个堆栈巧妙的实现撤销操作。

这里需要注意的是,堆栈中存放的都是NSInvocation实例。


还有就是setLevelsOfUndo方法,它设定了你最多可以撤销的次数


下面是一个从网上看到的源码,以供参考



-(void)undo
{
    [self.undoManage undo];
}
-(void)redo
{
    [self.undoManage redo];
}
-(void)apper
{
    
    if (!num) {
        self.navigationItem.rightBarButtonItem=nil;
    }
    else
    {
        if (self.undoManage.canUndo) {
            UIBarButtonItem*right=[[UIBarButtonItem alloc] initWithTitle:@"undo" style:UIBarButtonItemStyleBordered target:self action:@selector(undo)];
            self.navigationItem.rightBarButtonItem=right;
            [right release];
        }
    }
    if (!num) {
        self.navigationItem.leftBarButtonItem=nil;
    }
    else
    {
        UIBarButtonItem*left=[[UIBarButtonItem alloc] initWithTitle:@"redo" style:UIBarButtonItemStyleBordered target:self action:@selector(redo)];
        self.navigationItem.leftBarButtonItem=left;
        [left release];

        
    }
}
-(void)sub
{
    num-=10;
    [[self.undoManage prepareWithInvocationTarget:self] add];
    label.text=[NSString stringWithFormat:@"%d",num];
    [self apper];
    
}
-(void)add
{
    num+=10;
    [[self.undoManage prepareWithInvocationTarget:self] sub];
    label.text=[NSString stringWithFormat:@"%d",num];
    [self apper];
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    label=[[UILabel alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
    UIButton*btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame=CGRectMake(150, 150, 100, 100);
    [btn setTitle:@"add" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [self.view addSubview:label];
    num=0;
    label.text=[NSString stringWithFormat:@"%d",num];
    undoManage=[[NSUndoManager alloc] init];
    [self.undoManage setLevelsOfUndo:999];
}


有一篇不错的参考文章:IOS开发之Cocoa编程—— NSUndoManager

你可能感兴趣的:(ios,redo,undo,NSUndoManager)