Data Passing
View Controllers
iOS Development
App Programming
Swift Language

Passing data between view controllers

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When working with multiple view controllers in iOS applications, it is essential to pass data between them efficiently. This ensures that the app's functionality and user experience remain seamless and intuitive. In iOS development, data passing can be achieved in several ways depending on the scenario and the architectural pattern you are using (e.g., MVC, MVP, MVVM, or VIPER). Below, we explore common methods such as segue, delegates, closures, notifications, and data stores, supplemented with examples in Swift, the most widely-used language for iOS development.

1. Segue-based data passing

When using storyboards, segues are the most straightforward method for passing data directly between view controllers. A segue is triggered when transitioning from one view controller to another, and you can pass data in the prepare(for:sender:) method.

Example:

swift
1override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
2    if segue.identifier == "showDetailSegue" {
3        if let destinationViewController = segue.destination as? DetailViewController {
4            destinationViewController.data = "Data to pass"
5        }
6    }
7}

In this example, data is assigned directly to a property of the destination view controller before the transition.

2. Using Delegates

Delegates are a design pattern that allows one object to send messages to another object when specific events happen. It's a powerful tool for passing data back from a destination view controller to the source view controller.

Example:

swift
1protocol DataDelegate: AnyObject {
2    func passData(data: String)
3}
4
5class DetailViewController: UIViewController {
6    weak var delegate: DataDelegate?
7    
8    func someMethod() {
9        delegate?.passData(data: "Data from DetailViewController")
10    }
11}
12
13class ViewController: UIViewController, DataDelegate {
14    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
15        if let destinationViewController = segue.destination as? DetailViewController {
16            destinationViewController.delegate = self
17        }
18    }
19
20    func passData(data: String) {
21        print("Received data: \(data)")
22    }
23}

3. Closure Callbacks

Closures can be used to create a callback mechanism to pass data. This is particularly useful for more complex data passing scenarios or when using programmatic UI code instead of segues.

Example:

swift
1class DetailViewController: UIViewController {
2    var onCompletion: ((String) -> Void)?
3
4    func didFinishTask() {
5        onCompletion?("Data from DetailViewController")
6    }
7}
8
9class ViewController: UIViewController {
10    func showDetailViewController() {
11        let detailViewController = DetailViewController()
12        detailViewController.onCompletion = { data in
13            print("Received data: \(data)")
14        }
15        present(detailViewController, animated: true, completion: nil)
16    }
17}

4. Notifications with NotificationCenter

NotificationCenter is a way to implement a broadcast mechanism, where one view controller can send notifications that multiple classes can listen to.

Example:

swift
1extension Notification.Name {
2    static let sendDataNotification = Notification.Name("sendDataNotification")
3}
4
5class DetailViewController: UIViewController {
6    func sendNotification() {
7        NotificationCenter.default.post(name: .sendDataNotification, object: "Data to pass")
8    }
9}
10
11class ViewController: UIViewController {
12    override func viewDidLoad() {
13        super.viewDidLoad()
14        NotificationCenter.default.addObserver(self, selector: #selector(handleData(_:)), name: .sendDataNotification, object: nil)
15    }
16
17    @objc func handleData(_ notification: Notification) {
18        if let data = notification.object as? String {
19            print("Received data via Notification: \(data)")
20        }
21    }
22}

5. Shared Data Stores

Using a shared data store or a singleton pattern, such as a centralized model, can be effective if many view controllers need access to the same data. However, this approach can lead to tightly coupled code and should be used with care.

swift
1class DataManager {
2    static let shared = DataManager()
3    var data: String?
4}
5
6class DetailViewController: UIViewController {
7    override func viewDidLoad() {
8        super.viewDidLoad()
9        DataManager.shared.data = "Updated Data"
10    }
11}
12
13class ViewController: UIViewController {    
14    func loadData() {
15        print("Data from DataManager: \(DataManager.shared.data ?? "")")
16    }
17}

Summary Table

MethodWhen to UseComplexityData Flow Direction
SegueWith StoryboardsLowForward
DelegatesFor customized back data passingMediumBackward (mostly)
ClosuresHighly customizable scenariosMediumBoth
NotificationsBroad, app-wide eventsLowBoth
Data StoresAccess from multiple pointsMediumBoth

Additional Considerations

  • Memory Management: When setting up closures and delegates, handle memory cycles carefully using [weak self] in closures and declaring delegate properties with weak.
  • Modularization: Each method has its scenario; consider the project structure and future maintenance when choosing a method.
  • Performance: Note that NotificationCenter can lead to high coupling and obscure logic paths, which may impact performance and debuggability.

Through these techniques, iOS developers can ensure their applications manage data flow cleanly and predictably across different parts of the application.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.