我刚开始在Swift中使用委托,我似乎不知道如何从不同的类与我的View通信。具体来说,我从App调用自定义类的函数,然后从该自定义类中调用我的View中的函数。我的基本设置,跟进这个问题,是:
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的委托?我知道我错过了一些显而易见的/直接的东西,但是我还没有明白那是什么。
发布于 2015-06-06 07:28:15
你的问题很难回答,因为你完全误解了协议的要点。
协议是用来定义功能的类型。符合此协议的类通过实现所需的方法提供指定的功能。
无法初始化协议。
因此,如果您的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")
}
}阅读更多关于代表团在此的信息。
https://stackoverflow.com/questions/30679869
复制相似问题