I have 2 view controller classes. I want to call a method of ViewController2 from ViewController, but the console gives me this error:
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
Here is my method in the ViewController class:
class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {
@IBAction func testButton(sender: AnyObject) {
ViewController2().setText("It's a Test!")
}
}
And here is some code from ViewController2:
class ViewController2: UIViewController {
@IBOutlet weak var directionsTextField: UITextView!
func setText(var fieldText:String){
directionsTextField.text = directionsTextField.text + "\n \n" + fieldText
}
}
I'd be glad for every help! :-)
Thank you in advance :)
I also get this:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
on the setText method...
Seems like directionsTextField
isn't yet there maybe(??)
You're pretty close to figuring it out yourself. The crash is because your directionsTextField
does not yet exist. Being an IBOutlet it won't come into existence before viewDidLoad
is called. How do you fix this?
You change your API for your SecondViewController
and give it a directionsText
property. Winding up with something like this:
@IBOutlet weak var directionsTextField: UITextView!
var directionsText = ""
override func viewDidLoad() {
super.viewDidLoad()
directionsTextField.text = directionsTextField.text + "\n\n\(directionsText)"
}
In your FirstViewController
you change your IBAction to match the new API of the SecondViewController
:
@IBAction func testButton(sender: AnyObject) {
let secondController = SecondViewController() // Felt a bit odd creating an instance without having a way of referencing it afterwards.
secondController.directionsText = "It's a test"
// Do what you want. (Perhaps pushing your secondController)
}