iOS开发中的NSUndoManager的undo和redo功能

以前保存账户登录数据时用过一次CoreData,最近在研究CoreData官方demo(CoreDataBooks)的时候,发现了一个有意思的功能undo/redo,也就是给我们弥补犯下犯错的功能,


一、简介

帮助文档上说,NSUndoManager就是一个通用的撤消堆栈,你可以注册一个回调函数,当对象的属性改变时,你可以通过调用该函数,进行撤消管理。可以看到NSUndoManager中有两个id类型的成员变量(private) _undoStack,和_redoStack,两个stack初始化时都是空的,里面可以存放NSInvocation类型的数据,NSInvocation中大致有methodSignature,argumentsRetained,target,selector这些属性。它封装了消息事件的一些信息。最关键的大概就是这几句话:initially, both stacks are empty. Recording undo operations adds to the undo stack, but the redo stack remains empty until undo is performed. Performing undo causes the reverting operations in the latest group to be applied to their objects. Since these operations cause changes to the objects’ states, the objects presumably register new operations with the undo manager, this time in the reverse direction from the original operations. Since the undo manager is in the process of performing undo, it records these operations as redo operations on the redo stack. Consecutive undos add to the redo stack. Subsequent redo operations pull the operations off the redo stack, apply them to the objects, and push them back onto the undo stack.大概意思就是,当进行一次操作时,undo operations记录着与当前操作相反信息的NSInvocation压入到_undoStack中,当进行undo operations时,_undoStack的栈顶元素出栈,记录着与栈顶元素的反相操作的NSInvocation压入到_redoStack中(这时NSInvocation中的信息是与原操作一样的,负负得正的原理)。

二、简单的实现

系统提供了- (void)registerUndoWithTarget:(id)target selector:(SEL)selector object:(nullable id)anObject、- (id)prepareWithInvocationTarget:(id)target,- (void)registerUndoWithTarget:(id)target handler:(void (^)(id target))undoHandler最后一种是iOS9新加入的,帮助文档上说,- (id)prepareWithInvocationTarget:(id)target方法执行时会调用- (void)forwardInvocation:(NSInvocation *)anInvocation。这就说明NSUndoManager重载了该方法。我们知道,当方法找不到函数体时在crash前会走转发流程,转发时在调用- (void)forwardInvocation:(NSInvocation *)anInvocation前会调用- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector方法,如果在我在测试的类中实现该方法,是能够被调用的。假如我注册一个变量a,并且对他注册一个撤消操作,当a值改变时,我是可以进行撤消 的,当撤消后通过redo可以重做。接下来贴出几行简单的代码:


registerUndoWithTarget:

prepareWithInvocationTarget:

  另外我们还可以为NSUndoManager添加一个通知中心,来监听其状态的变化,需要注意的是在何时的地方移除监听。


 
                                      
demo地址: https://github.com/luguoliang/Model.git


原文链接:http://www.jianshu.com/p/57c33f4cf4b9
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值