D
D
Darkness2020-03-03 21:31:46
Swift
Darkness, 2020-03-03 21:31:46

Where is my error in delegation?

I know that a similar question has already been asked by me , but I still don't understand what I'm doing wrong! I sat for about 2 days looking at all the possible lessons and explanations, in my head everything fits into these explanations, BUT it does not work! I hope you shed some light, I have no one else to turn to.
So the simplest example what I am trying to do is:
1) MainViewController

//Создаю протокол
protocol MainViewControllerDelegate {
  func sayHello()
}
// в override
 var delegate: MainViewControllerDelegate?

// пытался и в другом месте, не знаю, можно ли вызывать метод делегата из override
// вызываю
delegate?.sayHello()

2) SecondViewController , which opens via segway from MainViewController
There:
- I subscribe the class to the delegate
.. , MainViewControllerDelegate
- I create a variable
var mainController = MainViewController()
B override:
mainController.delegate = self
And on the advice of XCODE I call the function
func sayHello() {
        print("Hey!")
    }


This print is not available.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Markov, 2020-03-03
@AntonBrock

The error is most likely here:
var mainController = MainViewController()
Since you are using segue, I suspect that your controller is created in a storyboard. And the call MainViewController()creates a new controller, which is not displayed anywhere.
You must set the delegate to prepare for segue in the class MainViewController:

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

You also need to use a weak reference to the delegate to avoid a retain cycle:
weak var delegate: MainViewControllerDelegate?
PS It's better to add more code, because it's not clear where exactly you are calling the delegate function. This phrase means nothing:
is it possible to call delegate method from override

The override keyword can appear in many places.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question