Using NSUndoManager and .prepare(withInvocationTarget:) in Swift 3

六月ゝ 毕业季﹏ 提交于 2019-12-01 04:11:58

prepareWithInvocationTarget(_:)(or prepare(withInvocationTarget:) in Swift 3) creates a hidden proxy object, with which Swift 3 runtime cannot work well.

(You may call that a bug, and send a bug report.)

To achieve your purpose, can't you use registerUndo(withTarget:handler:)?

undoManager?.registerUndo(withTarget: self) {targetSelf in
    targetSelf.undo(data, moreData: moreData)
}

I've had the same issue and I wasn't prepared to drop iOS 8 and macOS 10.10 support or go back to Swift 2.3. The registerUndo(withTarget:handler) syntax is nice though, so I basically just rolled my own version of that:

/// An extension to undo manager that adds closure based
/// handling to OS versions where it is not available.
extension UndoManager
{
    /// Registers an undo operation using a closure. Behaves in the same wasy as 
    /// `registerUndo(withTarget:handler)` but it compatible with older OS versions.
    func compatibleRegisterUndo<TargetType : AnyObject>(withTarget target: TargetType, handler: @escaping (TargetType) -> ())
    {
        if #available(iOS 9.0, macOS 10.11, *)
        {
            self.registerUndo(withTarget: target, handler: handler)
        }
        else
        {
            let operation = BlockOperation {
                handler(target)
            }
            self.registerUndo(withTarget: self, selector: #selector(UndoManager.performUndo(operation:)), object: operation)
        }
    }

    /// Performs an undo operation after it has been registered
    /// by `compatibleRegisterUndo`. Should not be called directly.
    func performUndo(operation: Operation)
    {
        operation.start()
    }
}

Hopefully it's helpful to someone else too.

Solution for backward compatibility with OS 10.10: use registerUndo(with Target: selector: object: ). No problem for saving single value. To save multiple values, I pack them into a dictionary and use that for the "object" parameter. For the undo operation, I unpack them from the dictionary, and then call the OS10.11+ undo method with those values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!