简体   繁体   中英

Swift can't call protocol method via delegate

I have two classes. One class is named ViewController and the other class is named TabView .

My goal is to call a function changeTab() which is inside the TabView class from the ViewController.

Somehow I am having trouble with it because everytime my delegate is nil .

Here is my code for ViewController:

protocol TabViewProtocol: class {
    func changeTab() 
}

class ViewController: NSViewController {
    // delegate
    weak var delegateCustom : TabViewProtocol?

    override func viewDidLoad() {
        print(delegateCustom) // outputs "nil"
    }

    buttonClickFunction() {
        print(delegateCustom) // outputs "nil"
        delegateCustom?.changeTab() // doesn't work
    }
}

Here is my code for TabView:

class TabView: NSTabViewController, TabViewProtocol {

    let myVC = ViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        myVC.delegateCustom = self
    }

    func changeTab() {
        print("test succeed")
    }
}

Can someone explain me what I am doing wrong? - I am new to delegates and protocols...

You are using the delegate pattern wrongly. It is hard to tell which controller you want to define the protocol for and which one you want to adopt it - but here is one possible way.

// 1. Define your protocol in the same class file as delegate property.
protocol TabViewProtocol: class {
    func changeTab() 
}

// 2. Define your delegate property
class ViewController: NSViewController {
    // delegate
    weak var delegateCustom : TabViewProtocol?

    override func viewDidLoad() {
        // It should be nil as you have not set the delegate yet.
        print(delegateCustom) // outputs "nil"
    }

    func buttonClickFunction() {
        print(delegateCustom) // outputs "nil"
        delegateCustom?.changeTab() // doesn't work
    }
}

// 3. In the class that will use the protocol add it to the class definition statement

class TabView: NSTabViewController, TabViewProtocol {

    let myVC = ViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        myVC.delegateCustom = self

        // Should output a value now
        print(myVC.delegateCustom) // outputs "self"
    }

    func changeTab() {
        print("test succeed")
    }
}

you are creating a new instance in this line:

let myVC = ViewController()

you should get existing instance of your ViewController.then set

myVC.delegateCustom = self

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM