Using NSUndoManager, how to register undos using Swift closures

喜你入骨 提交于 2019-12-01 21:12:14

What you're looking for is mutual recursion. You need two functions, each of which registers a call to the other. Here are a couple of different ways to structure it:

  1. In doThing(), register the undo action to call undoThing(). In undoThing, register the undo action to call doThing(). That is:

    @IBAction func doThing() {
        undoManager?.registerUndoWithTarget(self, handler: { me in
            me.undoThing()
        })
        undoManager?.setActionName("Thing")
    
        // do the thing here
    }
    
    @IBAction func undoThing() {
        undoManager?.registerUndoWithTarget(self, handler: { me in
            me.doThing()
        })
        undoManager?.setActionName("Thing")
    
        // undo the thing here
    }
    

Note that you should not refer to self in the closure unless you capture it with weak, because capturing it strongly (the default) may create a retain cycle. Since you're passing self to the undo manager as target, it's already keeping a weak reference for you and passing it (strongly) to the undo block, so you might as well use that and not reference self at all in the undo block.

  1. Wrap the calls to doThing() and undoThing() in separate functions that handle undo registration, and connect user actions to those new functions:

    private func doThing() {
        // do the thing here
    }
    
    private func undoThing() {
        // undo the thing here
    }
    
    @IBAction func undoablyDoThing() {
        undoManager?.registerUndoWithTarget(self, handler: { me in
            me.redoablyUndoThing()
        })
        undoManager?.setActionName("Thing")
        doThing()
    }
    
    @IBAction func redoablyUndoThing() {
        undoManager?.registerUndoWithTarget(self, handler: { me in
            me.undoablyDoThing()
        })
        undoManager?.setActionName("Thing")
        undoThing()
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!