问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/28016699/nil-when-unwrapping-an-optional-value-in-didbecomeactive