Search code examples
iosswiftswift-protocolsdelegation

Delegation to another view controller is not working


My sender class for delegation:

import UIKit

protocol tapDelgation:class {
    func tapConfirmed(message:String)
}

class ViewController: UIViewController {
    weak var delegate:tapDelgation?

    @IBAction func deligateSenderAction(_ sender: Any) {
        var data = "hello world"
        print(data)
        self.delegate?.tapConfirmed(message: data)
    }
}

My reciever class:

import UIKit

class NextViewController: UIViewController {
    weak var vc:ViewController? =  ViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        vc?.delegate = self
    }
}

extension  NextViewController : tapDelgation {
    func tapConfirmed(message: String) {
        print(message)
    }
}

What is expected: A button on sender vc is pressed and from reciever vc a console print would be popped. But in vain, nothing happens. Does any one know why it is happening? If it is not possible then why?


Solution

  • It looks like a memory management problem to me.

    First problem: Creating a view controller with a default initializer like ViewController() is almost never the right thing to do. because it won't have any view contents.

    You don't explain how your NextViewController and your ViewController get created and displayed.

    It looks like NextViewController has a weak reference to ViewController, and ViewController's delegate point is also weak (delegate references should almost always be weak.)

    This line:

    weak var vc:ViewController? =  ViewController()
    

    Will cause NextViewController to create an instance of ViewController that isn't owned by anybody, so it will immediately be deallocated and the vc variable will go back to being nil. By the time you get to NextViewController's viewDidLoad, vc will be nil, so the optional binding in the line vc?.delegate = self won't do anything.

    NextViewController's vc variable should almost certainly be a strong reference, not weak, but you don't show how ViewController ever gets displayed to the screen, so it isn't clear what you're trying to do.