使用NSUndoManager从异步撤消注册重做操作

时间:2019-10-30 01:01:29

标签: cocoa nsundomanager

使用UndoManager.registerUndo(withTarget:selector:object :)我可以注册一个撤消操作,然后在提供的选择器中调用该相同方法再次导致重做操作的注册。除非在选择器中我调用一个异步函数,然后需要注册重做操作,如下所示,否则此方法工作正常:

func job() {  
     doSomething()  
     registerUndo(self, undo)  
}  

func undo() {  
     async {  
          doSomethingElse()  
          registerUndo(self, job)  
     }  
}  

在这种情况下,两个对registerUndo()的调用实际上都注册了一个撤消操作,而不是我所期望的撤消然后是重做。 有解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:0)

我发现有一个连贯的 do/undo/redo 机制的更好的解决方案是使用 Action 对象


class Action {
    var someContextInfo ( like added/removed elements and indexes )
    var actionType ( like add/remove )

    func execute()

    // Returns the symmetric action ( for example `add` will be a `remove` )
    var symmetric: Action 
}

func doAction(action: Action) {  
     action.execute()  
     manager.registerUndo(withTarget: self) { target in
         target.doAction(action.symetric)
     }
}  

使用此解决方案可以执行/撤消/重做异步操作,因为您可以保留上下文并跟踪操作(完成、失败、进行中......)。

但正如评论中所说,这是一种不常见的情况。

相关问题