NSViewController委托?

时间:2015-06-06 06:50:42

标签: swift cocoa

我是在Swift中使用委托的新手,我似乎无法弄清楚如何从不同的类与我的View Controller进行通信。具体来说,我从我的App Delegate调用自定义类的函数,然后从该自定义类中调用我的View Controller中的函数。我的基本设置following this question是:

AppDelegate.swift:

var customClass = customClass()
func applicationDidFinishLaunching(aNotification: NSNotification) {
    customClass.customFunction()
}

CustomClass.swift:

weak var delegate: ViewControllerDelegate?
func customFunction() {
    delegate?.delegateMethod(data)
}

ViewController.swift:

protocol ViewControllerDelegate: class {
    func customFunction(data: AnyObject)
}
class ViewController: NSViewController, ViewControllerDelegate
    func customFunction(data: AnyObject){
        println("called")
    }
}

但是,delegate始终是nil。我假设这是因为ViewControllerDelegate协议永远不会被初始化,或者因为我从未设置实际NSViewController的委托?我知道我错过了一些明显/直接的东西,但是我还没有看到它是什么。

1 个答案:

答案 0 :(得分:1)

你的问题很难回答,因为你完全误解了协议的要点。

协议是一种用于定义功能的类型。符合此协议的类通过实现所需方法来提供指定的功能。

您无法初始化协议。

因此,如果您的CustomClass看起来像这样:

class CustomClass {
    weak var delegate: ViewControllerDelegate?
    func customFunction() {
        delegate?.delegateMethod(data)
    }
}

为什么期望delegate突然有价值?

当然,您必须先将delegate设置为某个内容。代表必须设置delegate。如果您希望ViewController实例成为委托,则必须将自己分配给delegate

这例如可行。

protocol ViewControllerDelegate {
    func delegateMethod(data: AnyObject) //I renamed this because in   
    //CustomClass you are trying to call `delegateMethod` on the delegate
}
class CustomClass {
    weak var delegate: ViewControllerDelegate?
    func customFunction() {
        delegate?.delegateMethod(data)
    }
}
class ViewController: NSViewController, ViewControllerDelegate

    var customClass = CustomClass()

    func viewDidLoad(){
        customClass.delegate = self
        customClass.customFunction() 
    }

    func delegateMethod(data: AnyObject){
        println("called")
    }
}

详细了解delegation here