Search code examples
iosswiftdelegatessegue

delegate remains nil


I'm trying to send data from one ViewController to another with delegate, but can't seem to get the right instance

I've tried setting the delegate at different places within the receiving ViewController including ViewDidLoad, but the delegate in the sending ViewController is always nil.

From what I've learned, it's an average problem everybody seems to go through, and I've read quite a number of samples, tried them, but to no avail. I don't know if I'm leaving something out or not. Please shed some light if you will.

Below is what I ended up with.

The sending ViewController:

protocol CreateChatDelegate: class{
    func appendChatData(_ sender: CreateChatViewController)
}

class CreateChatViewController: UIViewController {
     weak var delegate: CreateChatDelegate!

    @IBAction func createChat(_ sender: AnyObject) {
    delegate?.appendChatData(self)

        if delegate == nil {
            print("delegate unsuccessful")
        } else {
            print("delegate successful")
        }
}

The receiving ViewController:


class ViewController: UIViewController{
    var createChatViewController: CreateChatViewController!
    override func viewDidLoad() {
        super.viewDidLoad()
    ...

    }
}

extension ViewController: CreateChatDelegate {  
    func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // get the reference to the ViewController
        self.createChatViewController = segue.destination as? CreateChatViewController

        // set it as delegate
        self.createChatViewController?.delegate = self
        print("ViewController: delegate successful")
        }
    }

    func appendChatData(_ sender: CreateChatViewController) {
        print("ViewController: CreateChatDelegate called")
    }

}

this code outputs "delegate unsuccessful", because delegate is always nil


Solution

  • The method you are using is incorrect. You should use the new one:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        ....
    }
    

    Notice the override keyword? if you don't see this when you are writing the viewController methods, It means that you are NOT calling the original method and misspelled the function signature.

    NOTE: if you are targeting older iOS and using older Xcode, the method name may be different, you should write the name of the method and let the AutoComplete help you with the correct one.