Nil when unwrapping an Optional Value in didBecome

2019-07-23 12:52发布

I'm incredibly confused with the following scenario in my UIViewController:

I have the following @IBOutlet which has a referencing outlet in my Storyboard.

class MainViewController: UIViewController {
    @IBOutlet weak var warningLabel: UILabel!
}

I then have this in my AppDelegate:

var mainViewController: BLEMainViewController?

func applicationDidBecomeActive(application: UIApplication) {
    let mainViewController: MainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("mainViewController") as MainViewController
    let viewController = UINavigationController(rootViewController: mainViewController)

    mainViewController.didBecomeActive()
}

When I set this inside didBecomeActive()

self.warningLabel.text = "something"

I get the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

However it works fine if I do the following inside:

override func viewWillAppear(animated: Bool) {
    self.warningLabel.text = "something"
}

If I do warningLabel.text = "something" I get the same error.

If I do warningLabel?.text = "something" it doesn't actually get set.

If I do self.warningLabel?.text = "something" it doesn't actually get set.

What on earth am I doing wrong exactly?

EDIT:

Fixed by adding the following to my UIViewController:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)

Then it executes the didBecomeActive() function when the device becomes active.

标签: swift uilabel
2条回答
Bombasti
2楼-- · 2019-07-23 13:17

Fixed by adding the following to my UIViewController:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)

Then it executes the didBecomeActive() function when the device becomes active.

查看更多
闹够了就滚
3楼-- · 2019-07-23 13:21

Your IBOutlet is not yet initialized at the end of your applicationDidBecomeActive. So, you are trying to access a property (.text) of an object which is not initialized. This cause the error.

You don't have any error when calling warningLabel?.text = "something" because the ? means that you want to access the .text property only if warningLabel is initialized (different from nil). That also explain why the text is not set in this case.

A good place to initialize your outlet property is in the viewDidLoad function of your mainViewController. At this point your outlet would be initialized.

查看更多
登录 后发表回答