gpt4 book ai didi

objective-c - 如何实现 NSDocument 方法 -canCloseDocumentWithDelegate :shouldCloseSelector:contextInfo: in Swift?

转载 作者:行者123 更新时间:2023-11-30 13:04:00 35 4
gpt4 key购买 nike

在我的应用程序中,NSDocument 子类任务关键型硬件 - 用户真的不想意外关闭文档!因此,我实现了 canCloseDocumentWithDelegate... 以显示 NSAlert 并在关闭前询问。

我现在正在尝试在用 Swift 编写的应用程序中实现同样的事情。

由于答案是异步出现的,因此“应该关闭”结果将传递给委托(delegate)上的回调,而不是简单地返回。在 -canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo: 的文档中,它说:

The shouldCloseSelector callback method should have the following signature:

- (void)document:(NSDocument *)doc shouldClose:(BOOL)shouldClose contextInfo:(void *)contextInfo

因此,由于有 3 个不同类型的参数,我无法使用简单的 performSelector:withObject: 样式方法 - 你必须使用 NSInitation。请注意,委托(delegate)的类型是id,并且上面的签名不会出现在任何正式协议(protocol)中——您不能简单地正常调用该方法。 (请参阅此 mailing list post 以了解如何完成此操作的示例)

现在的问题是,Swift 中不允许 NSInitation!请参阅 Swift 博客 “What Happened to NSMethodSignature” :

Bringing the Cocoa frameworks to Swift gave us a unique opportunity to look at our APIs with a fresh perspective. We found classes that we didn't feel fit with the goals of Swift, most often due to the priority we give to safety. For instance, some classes related to dynamic method invocation are not exposed in Swift, namely NSInvocation and NSMethodSignature.

这听起来像是一件好事,但是当一个简单的 NSDocument API 仍然需要 NSInitation 时,就会失败!整个问题的真正解决方案是 Apple 引入一个使用 block 回调的新 canCloseDocument... API。但在此之前,最好的解决方案是什么?

最佳答案

您可以使用一些低级运行时函数来解决此问题:

override func canCloseDocumentWithDelegate(delegate: AnyObject, shouldCloseSelector: Selector, contextInfo: UnsafeMutablePointer<Void>) {

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>) -> Void
let function = unsafeBitCast(method, signature.self)

function(delegate, shouldCloseSelector, self, allowed, contextInfo)
}

如果您需要将此行为移至另一个方法(例如,在工作表获得用户确认后),只需将委托(delegate)和 shouldCloseSelector 存储在属性中,以便稍后访问它们。

关于objective-c - 如何实现 NSDocument 方法 -canCloseDocumentWithDelegate :shouldCloseSelector:contextInfo: in Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39599430/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com