NSResponder子类(macOS)中的UndoManager

时间:2019-05-10 13:14:01

标签: swift macos nsundomanager

我正在尝试在模型中实现撤消/重做。因此,我将模型类设为NSResponder的子类,然后实现了以下内容:

注释:根据注释后的更多研究来编辑此代码

func setAnnotations(_ newAnnotations: [Annotation]) {
    let currentAnnotations = self.annotations

    self.undoManager.registerUndo(withTarget: self, handler: { (selfTarget) in
        selfTarget.setAnnotations(currentAnnotations)
    })

    self.annotations = newAnnotations
}

Annotation是一个结构。

闭包内部的代码永远不会执行。最初,我注意到undoManagernil,但后来我发现了以下代码段:

private let _undoManager = UndoManager()
override var undoManager: UndoManager {
   return _undoManager
}

现在undoManager不再为nil,但是闭包内部的代码仍未执行。

我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

由于您已使撤消注册代码有意义,因此我无法重现任何问题。这是测试应用程序的 entire 代码(我不知道注释是什么,所以我只使用了String):

import Cocoa
class MyResponder : NSResponder {
    private let _undoManager = UndoManager()
    override var undoManager: UndoManager {
        return _undoManager
    }
    typealias Annotation = String
    var annotations = ["hello"]
    func setAnnotations(_ newAnnotations: [Annotation]) {
        let currentAnnotations = self.annotations
        self.undoManager.registerUndo(withTarget: self, handler: { (selfTarget) in
            selfTarget.setAnnotations(currentAnnotations)
        })
        self.annotations = newAnnotations
    }
}

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    let myResponder = MyResponder()
    @IBOutlet weak var window: NSWindow!
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        print(self.myResponder.annotations)
        self.myResponder.setAnnotations(["howdy"])
        print(self.myResponder.annotations)
        self.myResponder.undoManager.undo()
        print(self.myResponder.annotations)
    }
}

输出为:

["hello"]
["howdy"]
["hello"]

因此,撤消工作正常。如果那不是您的事情,那么也许您是在某种程度上管理“模型类”。


顺便说一句,写您的注册结束语更正确的是:

    self.undoManager.registerUndo(withTarget: self, handler: {
        [currentAnnotations = self.annotations] (selfTarget) in
        selfTarget.setAnnotations(currentAnnotations)
    })

这可确保不会过早捕获self.annotations