Kevin Griffin Kevin Griffin - 11 months ago 72
Swift Question

How do I register NSUndoManager in Swift?

How do I use

in Swift?

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

[[undoManager prepareWithInvocationTarget:self] myArgumentlessMethod];

Swift, however, seems to not have
, which (seemingly) means I can't call methods on the
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

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 Source

I tried this in a Playground and it works flawlessly:

class UndoResponder: NSObject {
    func myMethod() {

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