-1

The variable latitude in ViewController1 is visible. Why is the variable from another ViewController empty? Whenever I run the code the .text property of ActualCoordinatesText label is empty...


class ViewControllerGpsMaps: UIViewController {



    @IBOutlet weak var ActualCoordinatesText: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func GetCoordinates(_ sender: Any) {
        GetActualCoordinates()
    }

    public func GetActualCoordinates() {

        let sb = storyboard?.instantiateViewController(withIdentifier: "ViewController1") as! ViewController

        ActualCoordinatesText.text = sb.latitude

    }

}

Thanks for the help!

vhristoskov
  • 2,074
  • 2
  • 16
  • 20
prem111
  • 63
  • 1
  • 7
  • where did you read about accessing the data this way? This is incorrect. Read this: https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers – Keshu R. Feb 07 '20 at 15:34
  • http://www.programmingios.net/dont-make-a-new-instance-by-mistake/ – matt Feb 07 '20 at 16:04

1 Answers1

0

You are recreating a new instance of ViewController1 that means that the data included is the initialized value...

If your ViewControllerGPSMaps is called by VieController1 you should use the prepare(for segue:, sender:) of the ViewController1 to "give" the data you want to transfer...

Zaphod
  • 6,758
  • 3
  • 40
  • 60
  • In viewcontroller1 I have a timer that changes variable ... prepare and segue every now and then it is used to prepare data and send .... I need to constantly receive new data from viewcontroller1 The only solution will be a notification center? – prem111 Feb 07 '20 at 15:57
  • No, better solutions will be to either use a delegate function to pass the data pack to the parent viewController, or to inject a closure into a variable on viewController1 and execute that every time there is data to pass back. – flanker Feb 07 '20 at 16:31
  • Can you give some example of the last solution? Thanks. – prem111 Feb 07 '20 at 16:56