macos - Swift 弱委托(delegate)运行时错误(访问错误)。漏洞?

标签 macos delegates swift

我在 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/

相关文章:

macos - self.window 总是 nil

c++ - 是否可以用 C++ 编写应用程序的核心,然后将 Obj-C 和 Cocoa 用于 UI?

c# - 无法将类型 `UnityEngine.Events.UnityAction<string>' 隐式转换为 `UnityEngine.Events.UnityAction'

ios - 以编程方式创建具有默认图标的导航项 IOS

python - 文件未找到错误: [Errno 2] No such file or directory: 'geckodriver' : 'geckodriver' with GeckoDriver and Python in MAC OS

ios - performSelector 可能会导致泄漏,因为它的选择器是未知的 IN Singleton Class/FUNCTION Pointer -Passing Function as parameter

c# - 处理任何类型的方法

swift - 在 String 中创建 NSRange 时崩溃

javascript - 网站如何区分是通过Web浏览器还是App进入网站?

swift - 从未使用过不可变值 'rate' 的初始化