How can you implement the NSDocument method -canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo: in Swift?

后端 未结 4 1414
粉色の甜心
粉色の甜心 2021-01-13 07:25

In my application, a NSDocument subclass mission-critical hardware – users really don’t want to close a document by accident! So, I’ve implemented canClos

4条回答
  •  离开以前
    2021-01-13 08:07

    You can solve this with some low level runtime functions:

    override func canCloseDocumentWithDelegate(delegate: AnyObject, shouldCloseSelector: Selector, contextInfo: UnsafeMutablePointer) {
    
        let allowed = true // ...or false. Add your logic here.
    
        let Class: AnyClass = object_getClass(delegate)
        let method = class_getMethodImplementation(Class, shouldCloseSelector)
    
        typealias signature = @convention(c) (AnyObject, Selector, AnyObject, Bool, UnsafeMutablePointer) -> Void
        let function = unsafeBitCast(method, signature.self)
    
        function(delegate, shouldCloseSelector, self, allowed, contextInfo)
    }
    

    If you need to move this behaviour to another method (eg. after a sheet gets confirmation from the user), simply store the delegate and shouldCloseSelector in properties so you can access them later.

提交回复
热议问题