首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSViewController代表?

NSViewController代表?
EN

Stack Overflow用户
提问于 2015-06-06 06:50:41
回答 1查看 1.1K关注 0票数 0

我刚开始在Swift中使用委托,我似乎不知道如何从不同的类与我的View通信。具体来说,我从App调用自定义类的函数,然后从该自定义类中调用我的View中的函数。我的基本设置,跟进这个问题,是:

AppDelegate.swift:

代码语言:javascript
复制
var customClass = customClass()
func applicationDidFinishLaunching(aNotification: NSNotification) {
    customClass.customFunction()
}

CustomClass.swift:

代码语言:javascript
复制
weak var delegate: ViewControllerDelegate?
func customFunction() {
    delegate?.delegateMethod(data)
}

ViewController.swift:

代码语言:javascript
复制
protocol ViewControllerDelegate: class {
    func customFunction(data: AnyObject)
}
class ViewController: NSViewController, ViewControllerDelegate
    func customFunction(data: AnyObject){
        println("called")
    }
}

然而,delegate始终是nil。我假设这要么是因为ViewControllerDelegate协议从未被初始化,要么是因为我从未设置过实际NSViewController的委托?我知道我错过了一些显而易见的/直接的东西,但是我还没有明白那是什么。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-06 07:28:15

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

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

无法初始化协议。

因此,如果您的CustomClass是这样的:

代码语言:javascript
复制
class CustomClass {
    weak var delegate: ViewControllerDelegate?
    func customFunction() {
        delegate?.delegateMethod(data)
    }
}

为什么您认为delegate突然有了一个值?

当然,您必须首先将delegate设置为某些内容。委托必须设置delegate。如果希望ViewController实例成为委托,则它必须将自身分配给delegate

例如,这是可行的。

代码语言:javascript
复制
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")
    }
}

阅读更多关于代表团在此的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30679869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档