Delegates between viewcontrollers in swift

Viewed 89

I am trying to implement delegates in my app between 2 view controllers to in order to reload tableView data in one of them, but when I press the button nothing happens, I've tested it with breakpoints, am I forgetting something in my implementation?

Sending ViewController

     protocol UpdateDelegate {
            func updateExerciseCells()
        }

        class ExerciseVC: UIViewController {


            var delegate:UpdateDelegate?


           @IBAction func saveWorkoutPressed(_ sender: Any) {

                exercise = Exercise(name: exerciseNameInput.text!, weight: weightInput.text!, reps: repsInput.text!, sets: setsInput.text!, difficulty: "")

                WorkoutService.instance.exercises.append(exercise!)


                self.delegate?.updateExerciseCells()

                dismiss(animated: true, completion: nil)

            }
}

Receiving ViewController

class WorkoutVC: UIViewController, UpdateDelegate {

    var alert:ExerciseVC = ExerciseVC()




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

 func updateExerciseCells() {
        //update table
    }

}
2 Answers

What is happening here is that you are creating ExerciseVC programatically, but your Main.storyboard is creating another one through the segue. So delegate is nil on the one created by the segue.

Add this function to your WorkoutVC:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ExerciseVC {
        vc.delegate = self
    }
}

You can delete the alert variable in your WorkoutVC and any references to it as the one you'll use is already instantiated by UIStoryBoard

According to your code you use IBAction method in class ExerciseVC, it means that you have this controller in Storyboard. But you initialize ExerciseVC like

var alert:ExerciseVC = ExerciseVC()

It is incorrect because in this case IBAction methods are never called. Try to use

let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "yourViewControllerID")
Related