簡體   English   中英

NSViewController委托?

[英]NSViewController delegate?

我是在Swift中使用委托的新手,而且似乎無法弄清楚如何與其他類的View Controller通信。 具體來說,我從App Delegate調用了自定義類的函數,然后從該自定義類中調用了View Controller中的函數。 在此問題之后 ,我的基本設置是:

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的委托? 我知道我缺少明顯/直率的東西,但是我還沒有看到那是什么。

您的問題很難回答,因為您完全誤解了協議的要點。

協議是用於定義功能的類型。 通過實現必需的方法,符合該協議的類可提供指定的功能。

您無法初始化協議。

因此,如果您的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")
    }
}

在此處閱讀有關授權的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM