0

I have two view controllers one is main ViewController in which at bottom i putted container view and that container is connected to another NewViewController which i want to show in main ViewController. I'm setting JSON data to NewViewController's label in ViewController it gives me error as fatal error : unexpectedly found nil while unwrapping an Optional value

ViewController.swift

let nvc = NewViewController()
func someFunction {
     let data = JSON as! NSDictionary
     let result = data["result"] as! NSArray
     let mytitle = result.valueForKey("name") as! NSArray
     let count = mytitle.count - 1
     for index in 0...count {
         let nameOfPlace = mytitle[index] as! String
         print(nameOfPlace) //prints all the names of places
         self.nvc.nameLabel.text = nameOfPlace //Thread 1:EXC_BAD_INSTRUCTION
     }

NewViewController.swift

@IBOutlet weak var nameLabel: UILabel!
Ishwar
  • 73
  • 9
  • Possible duplicate of [fatal error: unexpectedly found nil while unwrapping an Optional value - why?](http://stackoverflow.com/questions/26348996/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-value-why) (specific) & [What does “fatal error: unexpectedly found nil while unwrapping an Optional value” mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) (canonical) – Hamish Jun 10 '16 at 11:51
  • Also your viewController should be created with the reference of your storyboard – Rajeev Bhatia Jun 10 '16 at 12:13

1 Answers1

0

Do not set any IBOutlet of your UIViewController before it is displayed.

The IBOutlet is probably not initialised yet. I would suggest making a string property, setting it when you initialise your UIViewController and setting that text to your UILabel in the viewDidLoad or viewWillAppear method.

Hope this helped!

Rajeev Bhatia
  • 2,974
  • 1
  • 21
  • 29