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
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