问题描述
我正在使用swift,并且显示了NSOpenPanel.在委托中,我需要查看发送者的提示以区分要采取的操作:
Im using swift and I show a NSOpenPanel. In the delegate I need to look at the sender's prompt to distinguish which action to take:
例如
func show() {
...
panel.delegate = self
panel.prompt = "xy"
panel.run ....
}
func show2() {
...
panel.delegate = self
panel.prompt = "abc"
panel.run ....
}
//delegate
func panel(sender: AnyObject, shouldEnableURL url: NSURL) -> Bool {
let panelPrompt = (sender as! NSOpenPanel).prompt ...
}
-
没有沙箱=可以正常工作
without sandbox = WORKS fine
- 委托的发送者确实是一个NSOpenPanel
带有沙箱=投射失败,崩溃
with sandbox = Cast fails, crash
- 委托的发送者不是NSOpenPanel,而是NSVBOpenPanel. Apple的私人课程,可以与外界进行远程对话,并允许用户选择通常不在您的沙箱中的文件. (有关详细信息,请参阅Apple的沙箱指南)
所以问题是如何在不崩溃的情况下迅速使用它?
有没有一种好的方法,或者只是一个错误/丑陋的IDK行为
我必须还原为使用performSelector吗?
So the question is how do I do use this in swift without crashing?
Is there a nice way or is it just a bug/ugly idk behavior
Do I have to revert to use performSelector?===
添加:NSOpenPanel的扩展也不起作用!
Addition: extensions to NSOpenPanel don't work either!
推荐答案
不是将发送方强制转换为
NSOpenPanel
(此操作失败是因为sender是私有NSVBOpenPanel
类的实例),或某些performSelector
魔术,您可以使用以下事实:可以在AnyObject
上访问任意方法和属性不强制转换,并且该调用的行为类似于隐式展开后可选:Instead of casting the sender to
NSOpenPanel
(which fails because thesender is an instance of the privateNSVBOpenPanel
class),or someperformSelector
magic, you can use the fact thatarbitrary methods and properties can be accessed onAnyObject
without casting, and the call behaves like an implicitlyunwrapped optional:func panel(sender: AnyObject, shouldEnableURL url: NSURL) -> Bool { let panelPrompt = sender.prompt ?? "" // ... return true }
这会提示您输入任何
sender
对象,该对象具有prompt
属性,并将空字符串作为后备.在我的测试中,效果很好在沙盒环境中.This gives the prompt for any
sender
object which has aprompt
property, and the empty string as a fallback. In my test it worked wellin a sandboxed environment.有关更多详细信息,示例,请参见 Swift的AnyObject的异常行为以及对文档.
See The strange behaviour of Swift's AnyObject for more details, examples, and references to thedocumentation.
这篇关于swift + OS X沙箱:将"NSVBOpenPanel"视为"NSOpenPanel" ::因为我需要在委托方法中获取发送者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!