本文介绍了在 didBecomeActive() 中解开可选值时为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 UIViewController 中的以下场景感到非常困惑:

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

我有以下 @IBOutlet,它在我的故事板中有一个引用插座.

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

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

然后我在我的 AppDelegate 中有这个:

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

当我在 didBecomeActive()

self.warningLabel.text = "something"

我收到以下错误:

致命错误:解包可选值时意外发现 nil

但是,如果我在内部执行以下操作,则效果很好:

However it works fine if I do the following inside:

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

如果我执行 warningLabel.text = "something" 我得到同样的错误.

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

如果我执行 warningLabel?.text = "something" 它实际上并没有被设置.

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

如果我执行 self.warningLabel?.text = "something" 它实际上并没有被设置.

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

我到底做错了什么?

通过将以下内容添加到我的 UIViewController 来修复:

Fixed by adding the following to my UIViewController:

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

然后在设备激活时执行 didBecomeActive() 函数.

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

推荐答案

您的 IBOutlet 尚未在您的 applicationDidBecomeActive 结束时初始化.因此,您正在尝试访问未初始化的对象的属性 (.text).这会导致错误.

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.

您在调用 warningLabel?.text = "something" 时没有任何错误,因为 ? 意味着您要访问 .text 属性仅在 warningLabel 被初始化时(不同于 nil).这也解释了为什么在这种情况下没有设置文本.

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.

初始化插座属性的好地方是在 mainViewControllerviewDidLoad 函数中.此时,您的插座将被初始化.

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

这篇关于在 didBecomeActive() 中解开可选值时为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:53