Segues Part 2: Passing Objects

iOS Development Tutorial

Learn to seamlessly pass data between Table View Controller and Detail View Controller using segues in iOS development. Gain a deep understanding of creating mutable arrays and connecting band detail outlets in code.

Key Insights

  • The tutorial covers creating mutable arrays and connecting band detail outlets in code in iOS development.
  • Students learn to pass data between the Table View Controller and the Detail View Controller using a segue, added in an earlier exercise.
  • The mutable arrays are created for band titles using 'let' for immutable objects and 'var' for mutable objects.
  • Mutable objects, unlike immutable objects, can be updated after creation.
  • The band detail outlets are connected with the code to allow them to be displayed on the view. This involves creating outlets for each element on the page.
  • The tutorial also guides users through the process of viewing and testing the application in a simulator, which helps visualize the results of the coding exercises.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

What This Tutorial Covers

  • prepare(for:sender:)

    Hook called before a segue executes.

  • Destination Setup

    Configure the next view controller's properties.

  • Segue Identifiers

    Distinguish between multiple segues from one VC.

Topics Covered in This IOS Development Tutorial:

Creating a Mutable Array, Connecting Band Detail Outlets in Code

Exercise Overview

In this exercise, you’ll learn how to pass data between the Table View Controller and the Detail View Controller via the segue we added in an earlier exercise.

Getting Started

  1. If you completed the previous exercise you can skip the following sidebar. We recommend you finish the previous exercises (1B–2A) before starting this one.

    If you completed the previous exercise, Jive Factory.xcodeproj should still be open. If you closed it, re-open it (from yourname-iOS Dev Level 2 Class > Jive Factory).

    If You Did Not Complete the Previous Exercises (1B–2A)

    1. Close any files you may have open and switch to the Desktop.
    2. Navigate to Class Files > yourname-iOS Dev Level 2 Class.
    3. Duplicate the Jive Factory Ready for More Segues folder.
    4. Rename the folder to Jive Factory.
    5. Open Jive Factory > Jive Factory.xcodeproj.
Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Creating a Mutable Array (Let Vs. Var)

We have the objects for our bands created, and now we need to be able to pass along the correct object depending on the row the user clicks. If you remember from a previous exercise, we used an array to hold the Titles for the different bands, then pulled the correct band title depending on what the user clicked. We need to do a similar thing for these objects. The arrays we created for bandTitles etc. are prefixed with let. When you use let you are creating a constant or immutable object. However, when you use var you are creating a mutable object. Only mutable objects are allowed to be updated after creation.

  1. In the Project navigator, click on BandsTableViewController.swift.
  2. Below the bandImageNames property, add the following bold code:

    let bandImageNames = ["thumb-nicole-atkins", "thumb-ambulance-ltd", "thumb-sleepies", "thumb-black-angels"]
    var bandDetails = [BandDetail]()
    
    override func viewDidLoad() {

    Notice that we use var to create a mutable object. We set the name of our object to bandDetails and we set the object to an array that contains the type BandDetail. In Swift an array must contain only one data type (in this case we set it to our custom object of BandDetail).

  3. Now that we have the bandDetails mutable array to work with, let’s add the BandDetail objects to it. Find the code for the last band object we created (blackAngelsDetails) and add the following bold code after it:

    blackAngelsDetails.showDetails = "Over 21—$15"
    
       bandDetails.append(nicoleAtkinsBandDetail)
       bandDetails.append(ambulanceLtdDetails)
       bandDetails.append(sleepiesDetails)
       bandDetails.append(blackAngelsDetails)
    }

    Because the structure of our app is getting more complex, below is a chart that explains how information will pass through it. Some parts we’ve already created, and the rest we’ll create in the remainder of this exercise.

    segues flow diagram

  4. In the Project navigator, click on BandsDetailViewController.swift.
  5. At the top, create a property called currentBandDetail by adding the bold code shown below:

    class BandsDetailViewController: UIViewController {
    
       var currentBandDetail:BandDetail?
    
       override func viewDidLoad() {
  6. Go to BandsTableViewController.swift.
  7. Near the bottom, add the bold code inside the prepare (for segue) method:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if (segue.identifier == "showDetail") {
          if let indexPath = self.tableView.indexPathForSelectedRow {
             let bandsDetailViewController:BandsDetailViewController = segue.destination as! BandsDetailViewController
             bandsDetailViewController.currentBandDetail = bandDetails[indexPath.row]
          }
       }
    }

    Let’s break this code down for you. We are setting the currentBandDetail object in the bandsDetailViewController equal to the object in the bandDetails mutable array at the specified indexPath.row. It figures out the correct indexPath.row based on the row that is clicked. If you remember, we set this in the first line of the code in the if statement. Awesome! Next we’ll get all the labels in the Detail View Controller displaying the correct info from the object that’s passed.

Connecting Band Detail Outlets in Code

Let’s connect each of our Band Detail elements with the code so that they will be displayed on the View.

  1. In the Project navigator click on Main.storyboard.
  2. If the Document Outline is open, click Hide Document Outline show hide document outline icon.
  3. Click the top bar of the Bands Detail View Controller so that it is selected in the Editor area.
  4. At the top right of the window, click the Assistant editor button assistant editor icon because we want to see the storyboard next to BandsDetailViewController.swift.
  5. If BandsDetailViewController.swift isn’t showing on the right side, choose it from the menu at the top of the code.
  6. You should now have the storyboard showing on the left and BandsDetailViewController.swift on the right. We are going to create outlets for each of the elements on this page.
  7. In the storyboard, make sure you can see the Bands Detail View Controller with all the placeholder labels (Name of Band, Type of music, etc.). You’ll probably have to scroll over to the right side of the storyboard.
  8. As shown below, hold Control or the Right mouse button and drag the Name of Band label to the BandsDetailViewController.swift file beneath the BandDetail property line.

    name of band drag insertOutlet

  9. In the menu that pops up, set the following:

    Name: bandNameLabel
    Storage: Weak
  10. Click Connect (or hit Return).
  11. Repeat this same process for the rest of the labels and the image, adding each just below the previous one. In the pop up menu, set Storage to Weak and Name to the following values:

    Type of music: bandTypeLabel
    Venue: venueLabel
    Date: showDateLabel
    Time: showTimeLabel
    Age / price: showDetailsLabel
    Description: bandDescriptionLabel
    Band image: bandImage
  12. When finished, the code you added should look like this:

    var currentBandDetail:BandDetail?
    @IBOutlet weak var bandNameLabel: UILabel!
    @IBOutlet weak var bandTypeLabel: UILabel!
    @IBOutlet weak var venueLabel: UILabel!
    @IBOutlet weak var showDateLabel: UILabel!
    @IBOutlet weak var showTimeLabel: UILabel!
    @IBOutlet weak var showDetailsLabel: UILabel!
    @IBOutlet weak var bandDescriptionLabel: UILabel!
    @IBOutlet weak var bandImage: UIImageView!
    
    override func viewDidLoad() {
  13. At the top right of the window, switch back to the Standard editor standard editor icon.
  14. In the Project navigator, select BandsDetailViewController.swift.
  15. Find the viewDidLoad method and add the following bold code:

    override func viewDidLoad() {
       super.viewDidLoad()
    
       // Do any additional setup after loading the view.
       bandNameLabel.text = currentBandDetail?.bandName
       bandTypeLabel.text = currentBandDetail?.bandType
       venueLabel.text = currentBandDetail?.venue
       showDateLabel.text = currentBandDetail?.nextShowDate
       showTimeLabel.text = currentBandDetail?.nextShowTime
       showDetailsLabel.text = currentBandDetail?.showDetails
       bandDescriptionLabel.text = currentBandDetail?.bandDescription
       bandImage.image = UIImage(named: currentBandDetail!.fullImageName!)
    }
  16. Click the Run button.
  17. When the Simulator loads, click on Nicole Atkins.

    The detail view will load. It should now be populated with the correct info!

  18. Click the Bands button at the top left to go back to the list of bands.
  19. Click on another band to go to the detail view and see it is populated with the correct info for that band as well.

    Notice the description at the bottom gets cut off. There should be two lines of description. Let’s fix that.

  20. Switch back to Xcode.
  21. Click the Stop button.
  22. In the Project navigator, click on Main.storyboard to view it.

    (If you don’t see it, click the Project navigator tab project navigator icon.)

  23. Click on the Description label to select it on the view.
  24. In the Attributes inspector attributes inspector icon, set Lines to 2 and hit Return.

    NOTE: This specifies the line limit. If the text is longer than the limit, it will be truncated and an ellipse (…) will be added at the end of the text. Setting the limit to 0 would give you an unlimited number of lines.

  25. Click the Run button.
  26. Click on any band (except for Nicole Atkins, which only has one line of content) to switch to the detail view. Notice the full 2-line description is now listed.
  27. Switch back to Xcode.
  28. Click the Stop button.
  29. Save the project and leave it open so we can continue to work on it in the next exercise.

Learn more in these courses

How to Learn IOS & Web Development

Master IOS Development, Web Development, Coding, and More with Hands-on Training. IOS Development Involves Designing Apps for Apple Mobile Devices with Tools Like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram