Passing data between view controllers

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Passing data between view controllers

📝 Passing Data Between View Controllers - A Beginner's Guide

Are you new to iOS development and struggling with passing data between view controllers? Don't worry, you're not alone! In this guide, we'll walk you through the common issues and provide easy solutions to help you overcome this hurdle.

🧩 Understanding the MVC Paradigm

Before we dive into passing data between view controllers, let's quickly revisit the Model-View-Controller (MVC) paradigm. MVC is a design pattern that separates an application's data (Model), user interface (View), and the logic that controls the interaction between the two (Controller).

In your case, the data entry form view acts as the View, the table view with multiple selections acts as another View, and the logic that handles data transfer between these two views is represented by the Controller.

💡 The Challenge: Transferring Data Across Views

Your challenge is to transfer the selected products from the table view to the data entry form view for further processing. Here are some common approaches to solve this problem:

1. Using Delegation

Delegation is a simple and effective way to pass data between view controllers. Define a protocol in the table view controller that allows the data entry form view controller to become its delegate. When a product is selected, call the delegate method to pass the selected data to the data entry form view controller. Here's a code snippet to help you visualize the process:

// In the TableViewController
protocol TableViewControllerDelegate: AnyObject {
    func didSelectProducts(_ selectedProducts: [Product])
}

class TableViewController: UITableViewController {
    weak var delegate: TableViewControllerDelegate?
    
    // ...
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedProduct = products[indexPath.row]
        delegate?.didSelectProducts([selectedProduct])
    }
}

// In the DataEntryFormViewController
extension DataEntryFormViewController: TableViewControllerDelegate {
     func didSelectProducts(_ selectedProducts: [Product]) {
         // Handle the selected products here
     }
}

2. Using Callback Closures

If you prefer a more lightweight approach, you can utilize callback closures. Declare a closure property in the table view controller and pass it to the data entry form view controller. When a product is selected, invoke the closure with the selected data. Here's an example:

// In the TableViewController
class TableViewController: UITableViewController {
    var didSelectProducts: (([Product]) -> Void)?
    
    // ...
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedProduct = products[indexPath.row]
        didSelectProducts?([selectedProduct])
    }
}

// In the DataEntryFormViewController
class DataEntryFormViewController: UIViewController {
    // ...
    
    func presentTableView() {
        let tableViewController = TableViewController()
        tableViewController.didSelectProducts = { [weak self] selectedProducts in
            // Handle the selected products here
        }
        present(tableViewController, animated: true, completion: nil)
    }
}

3. Using a Shared Data Model

Another approach is to create a shared data model, where both view controllers can access and modify the same instance of the data model. The data model can be a singleton or stored in an appropriate object, such as an app delegate or a dedicated data manager. However, it's worth noting that excessive use of singletons can make your code complex and harder to maintain.

🌟 Choose the Right Solution

Now that you have a few possible solutions, consider the specifics of your app and decide which approach best suits your needs. Consider factors such as the complexity of your data, the relationship between the view controllers, and the scalability of your app.

🙌 Engage and Share Your Experience

We hope this guide has shed some light on the process of passing data between view controllers. If you found it helpful, don't forget to share it with other iOS developers who might also benefit from it. Have any other questions or facing a different challenge? Let us know in the comments below! Happy coding! 👩‍💻💻👨‍💻

*[UITableViewController]: User Interface Table View Controller

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my