Kevin Griffin Kevin Griffin - 2 months ago 21
Swift Question

How do I register NSUndoManager in Swift?

How do I use

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?

Answer

I tried this in a Playground and it works flawlessly:

class UndoResponder: NSObject {
    func myMethod() {
        println("Undone")
    }
}

var undoResponder = UndoResponder()
var undoManager = NSUndoManager()
undoManager.registerUndoWithTarget(undoResponder, selector: Selector("myMethod"), object: nil)
undoManager.undo()