Everything about iOS app development

Pass objects between viewcontrollers in Swift

Post Series: Create an iOS app

One of the most important features that you must implement is passing objects between two viewControllers. There are couple of ways of doing it, one of them is using the performSegue method.

To pass an object from one viewcontroller to another is crucial in any software, let’s say you are creating an app that offers cars for sale, how would the user find out more informations about those cars, if they cannot tap on them to see the detailed information?

If you are a beginner and have no idea how to do it, please follow along, you’ll learn a few things and get closer to your final working iOS app.

There are two ways to pass objects between 2 UIViewControllers

There are more than that btw…

First way is the manual way, when you initialise your viewcontroller which you wish to pass objects to, and assign the select object to that UIViewController. This is the old method, but certainly works as it did before UIStoryboardSegues were introduced.

 

As you can see, you need to do the following things:

  1. Initialise your viewController
    1. I’m doing it now through UIStoryboard using the identifier specified for the viewcontroller in the storyboard
    2. Note: we need to wrap the initialising into an if statement to make sure that the initialised viewController’s class is the same that we are looking for
  2. Assign the selected object (selectedCar) to the viewController’s property (selectedCar)
  3. And finally present the viewController, in this example by pushing it to the navigation stack

 

The 2nd way of doing this is pretty simple. Just with the help of UIStoryboardSegues.

As you can see we only need 1 line for this call.

  1. Grab the object with the selected indexPath
  2. Perform the segue with the identifier that we specified in our storyboard
  3. Pass in the selected object as the sender

But this wouldn’t work properly, as we didn’t tell Xcode what it should do with the selectedCar object. Therefore we need to override the prepareForSegue method, so that we can assign the object to our destination viewcontroller.

Here is how:

In this method we need to do the following things:

  1. Check if the segue’s identifier is the one that we actually want, since we can have several segues for the same viewController, so we need to differentiate which one we need now.
  2. Check if the sender is the right class (Car) and if the segue.destination is equal to our destination viewcontroller in this case the DetailViewController.
  3. If those are true, pass the selected object to the viewController. Note: we don’t need to call the push or present methods here.

 

Learn more about UIStoryboardSegues here.

Hope you enjoyed it, and learn something today too, if you did, like, comment and share. (I know this is super beginner level, but everyone was a newbie once.)