Сбой функции загрузки из другого класса в Swift IOS

#ios #swift #function #debugging #crash

#iOS #swift #функция #отладка #сбой

Вопрос:

Я хочу загрузить функцию checkStatus() (которая является частью моего viewController1) из моего ViewController 2, прежде чем навигационный контроллер вернется к viewController1. К сожалению, при вызове функции приложение вылетает сразу после загрузки, и я действительно расстроен, потому что я не знаю, что я сделал не так.

ViewControllers встроены в навигационный контроллер.

Код в viewController1:

 func checkStatus(){
/* setting Label texts (Outlets) to a specific value but it is 
irrelevant as the compiler does not even get to 
    this point. The program crashes as soon as the function is called (tried it with prints).*/
  

Код в ViewController2:

 @IBAction func didTapBack(_ sender: UIButton){
// first the function is animating something inside the VC2
ViewController1().checkStatus() // function gets called here
self.navigationController?.popToRootViewController(animated: false)
}
  

Я благодарен за любую помощь.

Комментарии:

1. Выполнение ViewController1() не даст вам ваш исходный существующий контроллер представления, а новый экземпляр, и, поскольку он не загружается из раскадровки, никакие выходы не работают. Вам следует изучить применение шаблона делегирования

Ответ №1:

Вы можете использовать шаблон делегирования для вызова функции в вашем случае.

Код ViewController:

 import UIKit

class ViewController: UIViewController, SecondViewControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    
}

@IBAction func gotoSecondVC(_ sender: UIButton) {
    
    let secondVC = self.storyboard?.instantiateViewController(identifier: "SecondViewController") as! SecondViewController
    secondVC.delegate = self
    self.navigationController?.pushViewController(secondVC, animated: true)
    
}

func checkStatus() {
    print("(#function) called...")
}

}
  

Код SecondViewController:

 import UIKit

protocol SecondViewControllerDelegate: class {
    func checkStatus()
}

class SecondViewController: UIViewController {

    weak var delegate: SecondViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func backButtonTapped(_ sender: UIButton) {
        delegate?.checkStatus()
        self.navigationController?.popViewController(animated: true)
    }

}