简体   繁体   中英

Can't call ViewController method from AppDelegate

In AppDelagate I call the following in a method

func example() {
    ViewController().test()
}

and In my ViewController the method is

func test() {
    testView.userInteractionEnabled = true
    buttonTapped(UIButton())
    restartTimer()
}

but it crashes whenever I call the method, due to a nil error with testView. testView is a view in ViewController and not in AppDelegate, but I don't know how to make it so the method executes like how it would if i called it in the ViewController.

An IBOutlet is nil until the view controller calls viewDidLoad . viewDidLoad did not occur since you tried to instantiate the class directly via the call ViewController() .

Thus, testView is nil, as expected. Your AppDelegate should not be responsible for the ViewController logic anyhow.

As you may know by now, your crash is happening due the fact you're accessing a IBOutlet before it get the chance to be initialized. So I'm guessing the testView is declared sort of like this:

@IBOutlet weak var testView: UIView!

Solution A

You can turn it optional instead to avoid this crash:

@IBOutlet weak var testView: UIView?

And change the syntax in your VC to:

testView?.userInteractionEnabled = true

Solution B

If you really need to turn the User Interaction off at this point, you can force the view to load:

let myVc = ViewController()
_ = myVc.view // this will force the myVc.view to be loaded
myVc.test()

This way your IBOutlet s will have the chance to initialize before you run the test() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM