简体   繁体   中英

Swift 4 - Can't call delegate method

I have one delegate method defined in one viewController like so:

import UIKit

protocol PatientsUserDelegate: NSObjectProtocol {

    func patientsUserDelegateMethod()

}

class PatientsUserController: UIViewController {

    var patientsUserDelegate: PatientsUserDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        print("Here")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func nextButtonPressed(_ sender: Any) {

        patientsUserDelegate?.patientsUserDelegateMethod()

    }

}

What I am trying to do is call this delegate method in another viewController like so:

class PatientsRegistration: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, PatientsUserDelegate {

   var patientsUserController = PatientsUserController()

    override func viewDidLoad() {

         patientsUserController.patientsUserDelegate = self

    }

    func patientsUserDelegateMethod() {
        print("Here")
    }

}

nextButtonPressed gets called but not the delegate method is not being called in the first viewController I have. What am I doing wrong?

The problem is this line:

var patientsUserController = PatientsUserController()

The trouble is that this is not the same PatientsUserController that you actually want to talk to. It is a new PatientsUserController, a different one, that just floats in mid-air, with no relation to your running program. Thus, when you set the delegate...

patientsUserController.patientsUserDelegate = self

...you have set the delegate of the wrong PatientsUserController.

This is such a common beginner mistake that I've written a blog post about it:

http://www.programmingios.net/dont-make-a-new-instance-by-mistake/

As you'll see when you read that post, you need to get yourself a reference to the real PatientsUserController, the one that is already existing in your view controller hierarchy. How you do that depends on the relationship between your various view controllers.

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