Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Found nil while setting UILabel? Swift

Hello,

In my App Delegate I have this code.

 func applicationDidBecomeActive(application: UIApplication) {

   var unacknowledgedNotifs:Int = application.applicationIconBadgeNumber application.applicationIconBadgeNumber = 0
       if unacknowledgedNotifs >= 1 {
            viewController.checkForNewRiddle()

       }

Im using this method to check for a notification badge and if there is one then i want to update a label in my viewController. So i call the method viewController.checkForRiddle() which is a function in my View controller that changes the label.

However, when i run this the app crashes, specifically when setting that label. It crashes with: fatal error: unexpectedly found nil while unwrapping an Optional value...

I've been playing around with different ideas and none of them seem to fix this issue. I thought the issue is most likely because the view hadn't loaded yet but when i was playing around I did println() in viewDidLoad, didFinishLaunching and didBecomeActive and found that actually the viewDidLoad was called first. Hence the complete confusion...

So my conclusion that the view not being loaded yet caused the crash must be false if that println statement came first.

I hope this makes some sense to someone and any help would be greatly appreciated. Been stuck on this for hours :|

Cheers.

2 Answers

Show me the code for the function? It looks like you're not casting what you want.

Below is basically what I'm doing. The bool for key is set in the app delegate methods I talked about before.

 func checkForNewRiddle() {        
   if userDefaults.boolForKey("shouldUpdate") == true {     
       mainLabel.text = "test...."
       userDefaults.setBool(false, forKey: "riddleHasBeenRevealed")
    }

Solution: Using NSNotificationCentre.