iOS设计模式(九) 命令模式

本文介绍了如何通过命令模式实现应用程序的撤销与恢复功能。重点讨论了Objective-C中的NSInvocation和NSUndoManager两种实现方式,包括它们的工作原理及具体使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以把一系列动作封装成一个命令,在用户不需要知道其实现细节,使用细节的情况下就可以调用。

一般在想让应用程序支持撤销与恢复的情况下使用这一模式。

在OC中NSInvocation和NSUndoManager是这个模式的两个实现。


NSInvocation

使用方法:
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:@selector(run:)];
    
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    
    [invocation setTarget:self];
    
    [invocation setSelector:@selector(run:)];
    
    NSString *str = @"haha";
    
    int d;
    
    [invocation setArgument:&str atIndex:2];
    
    [invocation invoke];
    
    [invocation getReturnValue:&d];
    
    NSLog(@"%d",d);

- (int) run:(NSString *) str{
    NSLog(@"run:%@",str);
    return 1;
}

NSUndoManager

工作原理:
当进行操作时,控制器会添加一个该操作的逆操作的invocation到Undo栈中。当进行Undo操作时,Undo操作的逆操作会倍添加到Redo栈中,就这样利用Undo和Redo两个堆栈巧妙的实现撤销操作。
undoManager的两个栈里面保存的都是invocation对象.

- (void) method1{

//    [[self.undoManager prepareWithInvocationTarget:self] run];
    [self.undoManager registerUndoWithTarget:self selector:@selector(run) object:nil];
}

- (void) method2{
    
    [self.undoManager undo];
}
其中 run 是一个undo的方法。

每次执行method1的时候就注册一个undo方法到栈里面。
然后每次执行undo的时候就会调用run方法。


method1中两个注册undo方法的方式都可以运行。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值