Accessing Variables from Another Swift iOS Class

0

I have a Main class in my application, and in it I have created the variable cod that receives the value of 0 , in this class I also have a sequence of buttons that in them contains the event of changing the value of% % , cod or 1 , and clicking after the click button, the application changes to another layout . In this other layout , matched by another class called 2 , I need to access the value of 3 , but when I use Resultado , it returns me the value of cod . even though the buttons have var dados = Main().cod , 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 result class

    var dados = Main().cod

What am I doing wrong that I can not access the changed value of 0 ?

    
asked by anonymous 14.04.2015 / 18:32

1 answer

1

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

The ideal is to pass this value through the ViewController you call, thus passing from "father to child."

Assuming your second class is ResultadoViewController and looks something like this:

class ResultadoViewController: UIViewController {
    var cod: Int!
}

Then the call of your button might look 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)
}
    
14.04.2015 / 18:57