Niklas
Niklas

Reputation: 75

Fatal error while unwrapping optional value in swift

I'm getting the following error when i try to update a label in swift.

fatal error: unexpectedly found nil while unwrapping an Optional value

There must be something I am missing. These are the two variables involved:

Label and Double variable

And this is the func where I seem to get the error:

Method to update label

As far as I can see the variable that I want to update the label with has a value of 19.875531899929 and I want the label to show the Int part of that. Where does the nil come from? I am stuck finding the bug.

Can the fact that I called the method from a ViewController instance in the applicationDidBecomeActive method of AppDelegate.swift have anything to do with it? This is the short code to call the method:

func applicationDidBecomeActive(application: UIApplication) {         

    viewControllerInstance.convertAlertTimeToCountdownFromMinutes() 

}

And the variable in AppDelegate.swift:

var viewControllerInstance = ViewController()

Upvotes: 1

Views: 96

Answers (1)

Nirav D
Nirav D

Reputation: 72410

Your UILabel object is nil, you forgot to connect your IBOutlet with your viewController's Label, try to connect the IBOutlet with UILabels named lblMinutes and lblMinutesTag.

New Edit

If you want to update the value of label when your app become active you can use NSNotificationCenter for that, add below code inside your viewController.

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationBecameActive:",
           name: UIApplicationDidBecomeActiveNotification,object: nil)
}

func applicationBecameActive(notification: NSNotification){
    self.convertAlertTimeToCountdownFromMinutes() 
}

deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

Upvotes: 2

Related Questions