www.pudn.com > NSManager-demo.zip > ViewController.m, change:2013-10-17,size:2771b


//
//  ViewController.m
//  撤销恢复
//
//  Created by msp on 13-10-17.
//  Copyright (c) 2013年 ___FULLUSERNAME___. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    UIButton * pBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [pBtn setFrame:CGRectMake(10, 10, 150, 30)];
    [pBtn setTitle:@"产生随机数" forState:UIControlStateNormal];
    [pBtn addTarget:self action:@selector(GenarateRandomNum:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pBtn];
    
    m_pLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 320, 30)];
    [m_pLabel setBackgroundColor:[UIColor clearColor]];
    [m_pLabel setText:@"请点击按钮来产生随机数"];
    [self.view addSubview:m_pLabel];
    [m_pLabel release];
    
    
    UIButton * pUndoBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [pUndoBtn setFrame:CGRectMake(10, 100, 150, 30)];
    [pUndoBtn setTitle:@"撤销" forState:UIControlStateNormal];
    [pUndoBtn addTarget:self action:@selector(Undo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pUndoBtn];
    
    UIButton * pRedoBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [pRedoBtn setFrame:CGRectMake(200, 100, 150, 30)];
    [pRedoBtn setTitle:@"恢复" forState:UIControlStateNormal];
    [pRedoBtn addTarget:self action:@selector(Redo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pRedoBtn];
    
    m_pMagager = [[NSUndoManager alloc] init];
    [m_pMagager setLevelsOfUndo:99];//可以撤销恢复99级
}

- (void)GenarateRandomNum:(UIButton*)pBtn
{
    NSMethodSignature * pSignature = [self methodSignatureForSelector:@selector(Undo:)];
    NSInvocation * pInvocation = [NSInvocation invocationWithMethodSignature:pSignature];
    [pInvocation setTarget:self];
    [pInvocation setSelector:@selector(Undo:)];
    [pInvocation setArgument:[m_pLabel text] atIndex:2];
    
    [[m_pMagager prepareWithInvocationTarget:self] Undo:[m_pLabel text]];//
    [m_pLabel setText:[NSString stringWithFormat:@"随机数:%d",arc4random()%100]];
}

- (void)Undo:(NSString*)text
{
    [[m_pMagager prepareWithInvocationTarget:self] Redo:[m_pLabel text]];
    [m_pLabel setText:text];
}

- (void)Redo:(NSString*)text
{
    [[m_pMagager prepareWithInvocationTarget:self] Undo:[m_pLabel text]];
    [m_pLabel setText:text];
}

- (void)Undo
{
    [m_pMagager undo];
}

- (void)Redo
{
    [m_pMagager redo];
}

- (void)dealloc
{
    [m_pMagager release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end