在Swift 3中使用NSUndoManager和.prepare(withInvocationTarget :)

jba*_*aga 7 macos nsundomanager swift3 xcode8

我正在将Xcode 7/Swift 2.2 mac OS X项目迁移到Xcode 8/Swift 3,我在我的视图控制器类MyViewController中使用undoManager遇到了一个问题,它有一个函数undo.

在Xcode 7/Swift 2.2中,这很好用:

undoManager?.prepareWithInvocationTarget(self).undo(data, moreData: moreData)
undoManager?.setActionName("Change Data)
Run Code Online (Sandbox Code Playgroud)

在Xcode 8/Swift 3中,使用https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html中推荐的模式

这应该改为:

if let target = undoManager?.prepare(withInvocationTarget: self) as? MyViewController {
    target.undo(data, moreData: moreData)
    undoManager?. setActionName("Change Data")
}
Run Code Online (Sandbox Code Playgroud)

但是,向MycastController的向下转换始终失败,并且未注册撤消操作.

我错过了一些明显的东西,或者这是一个错误?

OOP*_*Per 10

prepareWithInvocationTarget(_:)(或prepare(withInvocationTarget:)在Swift 3中)创建一个隐藏的代理对象,Swift 3运行时无法正常运行.

(您可以将其称为错误,并发送错误报告.)

为达到你的目的,你不能用registerUndo(withTarget:handler:)吗?

undoManager?.registerUndo(withTarget: self) {targetSelf in
    targetSelf.undo(data, moreData: moreData)
}
Run Code Online (Sandbox Code Playgroud)