如何在您的数据模型中创建警报,并在您的 ViewController 中将其作为参数调用

How to create an alert in your Data Model, and call it in your ViewController as a parameter

目前我正在尝试在模型中添加警报 Class。我添加 ViewController 作为参数,所以

viewController.present(alertView, animated: true)

看起来像

class DataClass { 
    func addAlert(viewController: UIViewController) {
        if let message = message {
            let alertView = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default) 
            alertView.addAction(okAction)

            viewController.present(alertView, animated: true)
        }
    }

然后在我的 ViewController

class mainVC: UIViewController {
    var mainVCVar: mainVC?

    override func viewDidLoad() {
        super.viewDidLoad()
        addAlert(viewController: mainVCVar) 
    }
}

我得到:

unexpectedly returned nil.

是否可以在同一个View Controller中调用自己的View Controller?

您传递的视图控制器与您从中调用函数的视图控制器不同。它为 nil,因为该视图控制器未实例化。

改为这样做:

addAlert(viewController: self)

首先,您需要一个 DataClass 对象。 其次,您需要在当前视图控制器上显示警报,即 self

class mainVC: UIViewController {
    var mainVCVar: mainVC?
    var dataClass = DataClass()
    override func viewDidLoad() {
        super.viewDidLoad()

        dataClass.addAlert(viewController: self)
    }
}