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

后端 未结 4 1444
粉色の甜心
粉色の甜心 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:08

    So, my current solution to this, is to keep using Objective-C to perform the NSInvocation. The NSDocument subclass is written in Swift, and calls an Objective-C category to do this bit of work.

    Since NSInvocation does not exist in Swift, I really don’t see any other way.

    - (void)respondToCanClose:(BOOL)shouldClose delegate:(id)delegate selector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo
    {
        NSDocument *doc = self;
    
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[delegate methodSignatureForSelector:shouldCloseSelector]];
        invocation.target = delegate;
        invocation.selector = shouldCloseSelector;
        [invocation setArgument:&doc atIndex:2]; // Note index starts from 2 - 0 & 1 are self & selector
        [invocation setArgument:&shouldClose atIndex:3];
        [invocation setArgument:&contextInfo atIndex:4];
    
        [invocation invoke];
    }
    

    You can see my sample project: https://github.com/DouglasHeriot/canCloseDocumentWithDelegate

    Another option is to use Objective-C to wrap around objc_msgSend, which is also unavailable in Swift. http://www.cocoabuilder.com/archive/cocoa/87293-how-does-canclosedocumentwithdelegate-work.html#87295

提交回复
热议问题