How to pass data from one Viewcontroller to another Viewcontroller

Asked

Viewed 1,456 times

0

Researching on this I found some solutions, the first is to go through the prepareForSegue(), the second is to use a shared variable (global), I also saw something about using protocol but could not use.

In some cases, an app that has multiple levels or uses a library like Swrevealviewcontroller(slide out menu), it is difficult to pass data and use global variables. I have always been recommended not to use in other programming languages.

Thus, according to best practices, how to pass data of a Viewcontroller to another.

  • I edited it to make it easier to read and tried not to be considered as "based on opinions"(see why).

  • I don’t know anything about Swift but if "protocol" is the equivalent of "interfaces" in Java and if an analogy can be made with Android, then using "protocol" can be a solution. Maybe this question can help you.

1 answer

0


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

Using properties of: Usually used when the die is passed only once, as soon as the object is allocated. I believe that was the way you did it. Define the properties of the second controller and when allocate it, modify the values of these 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 form is through protocols, as @ramaral suggested, see question which treats it. We usually use protocols when data is passed asynchronously. Ex: The second controller requests data from the first on demand as the user scrolls on the screen. I suggest studying the patterns delegate and datasource, widely used in iOS.

Another widely used standard for communication is the Singleton, but it should not be used for direct communication between two objects. Singletons are best used to maintain the overall status of the application.

Browser other questions tagged

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