How to pass data from one ViewController to another ViewController

0

Searching for this I found some solutions, the first is to go through prepareForSegue() , the second is to use a shared variable (global), I also got to see something about using protocol, but could not use it.

In some cases, where an app that has multiple levels or uses a library like SWRevealViewController (slide out menu), it is difficult to keep passing data and using global variables. I've always been advised not to use it in other programming languages.

So, according to best practices, how to pass data from one ViewController to another.

    
asked by anonymous 16.01.2016 / 14:39

1 answer

0

There are several ways to pass information between objects and the right way will depend on the characteristics of the application.

Using properties: Usually used when the data is passed only once, as soon as the object is allocated. I think that was the way you did it. You define the properties of the second controller and when you allocate it, modify the values of those properties:

class SecondViewController: UIViewController {

    var data: String?
}

class FirstViewController: UIViewController {

    ...
    //Utilizando segues para transição
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if let destinationViewController = segue.destinationViewController as? SecondViewController {
            destinationViewController.data = "foo"
        }
    }

    //Definindo as transições programaticamente
    @IBAction func openDetail(sender: UIView) {

        let destinationViewController = SecondViewController(nibName: "SecondViewController", bundle: nil)
        destinationViewController.data = "foo"
        presentViewController(destinationViewController, animated: true, completion: nil)
    }
}

Protocols: Another widely used is through protocols, as suggested by @ramaral, see

16.01.2016 / 16:31