MyLocations: issue with unwrapping "coordinate" in "TagLocation" segue [SOLVED]

Hi, I’m currently on page 195 of the MyLocations tutorial.

When I try to tag a new location the app crashes when I tap the “Tag Location” button with the following error message

fatal error: unexpectedly found nil while unwrapping an Optional value

on this line

controller.coordinate = location!.coordinate

of the prepareForSegue function of CurrentLocationViewController

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "TagLocation" {
      let navigationController = segue.destinationViewController as! UINavigationController
      let controller = navigationController.topViewController as! LocationDetailsViewController
      
      controller.coordinate = location!.coordinate
      controller.placemark = placemark
      controller.managedObjectContext = managedObjectContext
      
      stopLocationManager()
    }

I checked and found no difference in this function to the source code for this chapter provided with the book.

I previously ran into the same issue whenever I tried the second time to tag a location, but I thought I’d figure it out later. Now that the app crashes whenever I try to tag a location I know I should have taken care of it earlier. :wink:

Maybe it has to do with me using Xcode 7.3 and Swift 2.2, but I’m not sure. Any help is highly appreciated!

On that line, you do location!, which is what goes wrong. The value of location should never be nil but for some reason in your case it is. Most likely there is a small error in your code (a } in the wrong place, for example).

Thanks for the hint.

I now know that the error is not in the CurrentLocationViewController, since I replaced my file with the corresponding one from the book and the app still crashes at the same line.

I’ll check the storyboard connections and the other files later and will update here when I found the cause for the crash.

After about 6 hours of debugging :persevere: I finally solved my problem:

Somehow I had connected the Tag Location button not only to the segue to LocationDetailsVC, but also to the @IBAction getLocation. And that function sets the location variable to nil.

How and why I made that mistake, I have no clue. But I am glad I solved it.

What I learned from this:

  • I have learned a lot about debugging, but still have way to go.
  • I should check the storyboard and its connections way earlier in my debugging process. That could have literally saved me hours in this case. :stuck_out_tongue_closed_eyes:
  • Trying to debug while being tired doesn’t work to well for me. :wink:

@hollance Thanks for writing these great tutorials and also doing support here in the forums on top of it. Really appreciated! :clap:

Glad you found it! Don’t think of this as wasted time, though. This is how you learn.