iosswiftnsundomanager

How do I register UndoManager in Swift?


How do I use UndoManager (previously NSUndoManager) in Swift?

Here's an Objective-C example I've tried to replicate:

[[undoManager prepareWithInvocationTarget:self] myArgumentlessMethod];

Swift, however, seems to not have NSInvocation, which (seemingly) means I can't call methods on the undoManager that it doesn't implement.

I've tried the object-based version in Swift, but it seems to crash my Playground:

undoManager.registerUndoWithTarget(self, selector: Selector("myMethod"), object: nil)

However it seems to crash, even with my object accepts an argument of type AnyObject?

What's the best way to do this in Swift? Is there a way to avoid sending an unnecessary object with the object-based registration?


Solution

  • I tried this in a Playground and it works flawlessly:

    class UndoResponder: NSObject {
        @objc func myMethod() {
            print("Undone")
        }
    }
    
    var undoResponder = UndoResponder()
    var undoManager = UndoManager()
    undoManager.registerUndo(withTarget: undoResponder, selector: #selector(UndoResponder.myMethod), object: nil)
    undoManager.undo()