【问题标题】:Loading function from another Class crashes in Swift IOS从另一个类加载函数在 Swift IOS 中崩溃
【发布时间】:2020-09-19 06:36:26
【问题描述】:

我想在导航控制器弹回 ViewController1 之前从我的 ViewController 2 加载函数 checkStatus()(它是我的 ViewController1 的一部分)。 不幸的是,在调用该函数时,应用程序一加载就崩溃了,我真的很沮丧,因为我不知道自己做错了什么。

ViewController 嵌入在导航控制器中。

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)
}

感谢任何形式的帮助。

【问题讨论】:

  • ViewController1() 不会给你原来的现有视图控制器,而是一个新的实例,因为它不是从情节提要加载的,所以没有插座是可用的。您应该考虑应用委托模式

标签: ios swift function debugging crash


【解决方案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)
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多