Access variables from another iOS Swift class

Asked

Viewed 993 times

0

I have a class Main in my application, and in it I have created the variable cod which receives the value of 0, in this class I also have a sequence of buttons that in them contain the event of changing the value of cod for, 1, 2 or 3, and clicking after the click on the button, the application is changed to another layout. In that other layout, matched by another class called Resultado, I need to access the value of cod, but when I use the var dados = Main().cod, it returns me the value of 0, i.e. as long as the buttons have the cod = 1, the variable is not being changed:

class Main: UIViewController {
    var cod = 0

    @IBAction func btnSp(sender: AnyObject) {
        var storyboard = UIStoryboard(name: "Main", bundle: nil)
        var controller = storyboard.instantiateViewControllerWithIdentifier("viewConsultas") as UIViewController
        self.presentViewController(controller, animated: true, completion: nil)

        cod = 1
    }
}

and in the resulting class

    var dados = Main().cod

what I’m doing wrong that I can’t access the altered value of cod?

1 answer

1

What happens is that by doing Main() you are creating a new instance of this class, then the variable value cod is the initial, which is 0.

Ideally you pass this value through the ViewController that you call, passing thus from "father to son".

Supposing your second class is a ResultadoViewController and be more or less like this:

class ResultadoViewController: UIViewController {
    var cod: Int!
}

So your button call can go like this:

@IBAction func btnSp(sender: AnyObject) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let resultadoController: ResultadoViewController = storyboard.instantiateViewControllerWithIdentifier("viewConsultas") as ResultadoViewController

    resultadoController.cod = 1

    presentViewController(resultadoController, animated: true, completion: nil)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.