我在 Swift (OSX) 中遇到委托(delegate)问题。我有一个 View ,通过弱引用连接到委托(delegate)。简化的代码可能是这样的:
protocol MyProtocol: class {
func protocolFunc() -> Int
}
class MyController : MyProtocol {
func protocolFunc() -> Int { return 2 }
}
class MyView : NSView {
weak var delegate: MyProtocol?
func grabData {
var data = delegate?.protocolFunc()
}
}
当调用 delegate?.protocolFunc()
时,应用程序崩溃并提示“访问错误”。就好像 MyController 实例消失了......但它没有。 MyController 实例位于 NSDocument 子类中;并且 View 的委托(delegate)已正确设置。
如果我声明委托(delegate)为strong
,崩溃就会消失。但问题是我希望委托(delegate)是弱
。这是怎么回事?在我看来,弱引用应该有效。
最佳答案
在撰写本文时(Xcode 6 Beta 5),弱委托(delegate)存在一个错误。目前,在修复该问题之前,您所能做的就是将 protocol MyProtocol: class
更改为 @objc protocol MyProtocol
并避免在协议(protocol)中使用任何纯 Swift 类。
关于macos - Swift 弱委托(delegate)运行时错误(访问错误)。漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25371390/