If your app has multiple User Interfaces (UIs), you’ll want to move data from one UI to the next. How do you pass data between view controllers in Swift?
Passing data between view controllers is an important part of iOS development. You can use several ways to do so, and all of them have distinct advantages and drawbacks.
The ability to pass data between view controllers with ease is affected by your choice of app architecture. App architecture affects how you work with view controllers, and vice versa.
In this app development tutorial, you’ll learn 6 different methods of passing data between view controllers, including working with properties, segues and NSNotificationCenter. You’ll start with the easiest approach, then move on to more complicated practices.
Table of Contents
- Passing Data Between View Controllers with Properties (A → B)
- Passing Data Between View Controllers Using Segues (A → B)
- Passing Data Back with Properties and Functions (A ← B)
- Passing Data Back with Delegation
- Passing Data Back with a Closure
- Passing Data Between View Controllers with NotificationCenter
- Conclusion
Passing Data Between View Controllers with Properties (A → B)
You can pass data between view controllers in Swift in 6 ways:- By using an instance property (A → B)
- By using segues with Storyboards
- By using instance properties and functions (A ← B)
- By using the delegation pattern
- By using a closure or completion handler
- By using NotificationCenter and the Observer pattern
- Initialization: Ensure that the destination view controller's properties are initialized before the transition. This can be done in the prepare(for:sender:) method of the source view controller.
- Safety: Always check for nil values when accessing properties in the destination view controller. Using optional binding (if let or guard let) can help safely unwrap these values.
- Data Types: Properties can be of any data type, including custom objects. Ensure that the data type of the property matches the type of data you want to pass.
- Performance: Passing data using properties is efficient, as it doesn't involve any overhead like serialization or database operations. However, be cautious when passing large data sets or objects, as it might impact memory usage.
- First, with the if statement and the is keyword you check whether the segue destination is of class TertiaryViewController. You need to identify if this is the segue you want to customize, because all segues go through the prepare(for:sender:) function.
- Then, you simply type cast segue.destination to TertiaryViewController, so you can use the username property. The destination property on segue has type UIViewController, so you’ll need to cast it to get to the username property.
- Finally, you set the username property, just like you did in the previous example.
Passing Data Back with Properties and Functions (A ← B)
Now… what if you want to pass data back from a secondary view controller to the main view controller? Passing data between view controllers using a property on the secondary view controller, as explained in the first chapter, is fairly straightforward. How do you pass data back from the second view controller to the first? You can do this in a couple of ways, as you’ll find out in the next sections. Here’s the scenario:- The user of your app has gone from view controller A to a secondary view controller B.
- In the secondary view controller the user interacts with a piece of data, and you want that data back in view controller A.
- Coupling: This method introduces tight coupling between the two view controllers. While it's straightforward, it can make the code less modular and harder to maintain in larger projects.
- Memory Management: Be cautious of retain cycles when using this approach. If both view controllers have strong references to each other, they might not be deallocated, leading to memory leaks. Using weak references can help mitigate this.
- Data Integrity: Ensure that the data passed back is validated and sanitized, especially if it's used for critical operations or displayed to the user.
- Function Calls: When using functions to pass data back, ensure that the function in the main view controller is prepared to handle multiple calls or unexpected data, as the secondary view controller might trigger it under various scenarios.
- The MainViewController and SecondaryViewController are now tightly coupled. You want to avoid tight-coupling in software design, mostly because it decreases the modularity of your code. Both classes become too entangled, and rely on each other to function properly, with often leads to spaghetti code.
- The above code example creates a retain cycle. The secondary view controller can’t be removed from memory until the main view controller is removed, but the main view controller can’t be removed from memory until the secondary view controller is removed. (A solution would be the weak property keyword.)
- Two developers can’t easily work separately on MainViewController and SecondaryViewController, because both view controllers need to have an understanding about how the other view controller works. There’s no separation of concerns.
Passing Data Back with Delegation
Delegation is an important and frequently used software design pattern in the iOS SDK. It’s critical to understand if you’re coding iOS apps! With delegation, a base class can hand off functionality to a secondary class. A coder can then implement this secondary class and respond to events from the base class, by making use of a protocol. It’s decoupled! Here’s a quick example:- Imagine you’re working in a pizza restaurant. You have a pizza baker that makes pizza.
- Customers can do anything they want with the pizza, like eat it, put it in the freezer, or share it with a friend.
- The pizza baker used to care about what you do with your pizza, but now he’s decoupled himself from the pizza-eating process and just throws you a pizza when it’s ready. He delegates the pizza handling process and only concerns himself with baking pizzas!
- Name the class MainViewController
- Extend (or subclass) the UIViewController class
- Implement (or conform to) the PizzaDelegate class
- You need a delegate protocol
- You need a delegate property
- The class that you want to off-hand data to, needs to conform to the protocol
- The class that you want to delegate from, needs to call the function defined in the protocol
- The developers that work on separate classes only need to agree on the protocol and the functions it has. Either developer can choose to conform and implement whatever they want.
- There’s no direct connection between the main view controller and the secondary view controller, which means that they’re more loosely coupled than the previous example.
- The protocol can be implemented by any class, not just the MainViewController.
Passing Data Back with a Closure
Using a closure to pass data between view controllers isn’t much different from using a property or delegation. The biggest benefit of using a closure is that it’s relatively easy to use, and you can define it locally – no need for a function or protocol. You start with creating a property on the secondary view controller, like this: var completionHandler: ((String) -> Int)? It’s a property completionHandler that has a closure type. The closure is optional, denoted by the ?, and the closure signature is (String) -> Int. This means the closure has one parameter of type String and returns one value of type Int. Once more, in the secondary view controller, we call the closure when a button is tapped: @IBAction func onButtonTap() { let result = completionHandler?("FUS-ROH-DAH!!!") print("completionHandler returns... \(result)") } In the example above, this happens:- The closure completionHandler is called, with one string argument. Its result is assigned to result.
- The result is printed out with print()
- You don’t need a complete delegation approach, with a protocol, you just want to create a quick function.
- You want to pass a closure through multiple classes. Without a closure you’d have to create a cascading set of function calls, but with the closure you can just pass the block of code along.
- You need to locally define a block of code with a closure, because the data you want to work with only exists locally.
Passing Data Between View Controllers with NotificationCenter
You can pass data between view controllers with Notification Center, via its NotificationCenter class. The Notification Center handles notifications, and forwards incoming notifications to components that are listening for them. The Notification Center is the iOS SDK’s approach to the Observer-Observable software design pattern.Quick Note: Since Swift 3, it’s called NotificationCenter – so no “NS” prefix. And keep in mind that these “notifications” aren’t push notifications. Working with Notification Center has three key components:- Observing the notification
- Sending the notification
- Responding to the notification
- You use NotificationCenter.default, which is the default Notification Center. You could create your own Notification Center, for instance for a certain kind of notifications, but chances are the default center is fine.
- You then call the function addObserver(_:selector:name:object:) on the Notification Center.
- The first argument is the instance that does the observation, and it’s almost always self.
- The second argument is the selector you want to call when the notification is observed, and this is often a function of the current class.
- The third parameter is the name of the notification, so you pass the static constant notificationName.
- The fourth parameter is the object whose notifications you want to receive. You usually pass nil here, but you could use it to only observe notifications from one particular object.
- You call the function post(name:object:userInfo:) on the default Notification Center, exactly the same center as you used before.
- The first function argument is the name of the notification, that static constant that you defined before.
- The second argument is the object posting the notification. You can often leave this nil, but if you’ve used the object argument when observing the notification you can pass the same object here to exclusively observe and post for that object.
- The third argument is the notification payload called userInfo. You can pass a dictionary with any kind of data here. In this example, you’re passing some data and a boolean value.
- The view controllers or other classes you want to pass data between are not closely related. Think about a table view controller that needs to respond when a REST API receives new data.
- The view controllers don’t necessarily have to exist yet. It could happen that the REST API receives data before the table view is put on screen. Observing for notifications is optional, which is an advantage if parts of your app are ephemeral.
- Many view controllers need to respond to one notification, or one view controller needs to respond to multiple notifications. Notification Center is many-to-many.
Conclusion
Passing data between view controllers is a fundamental aspect of iOS development, enabling seamless user experiences and dynamic interactions within apps. Whether you're using properties, segues, delegation, or other techniques, it's crucial to choose the approach that best fits the specific needs of your app. In conclusion, while the mechanics of passing data might seem straightforward, the underlying decisions about which method to use can significantly impact the robustness and efficiency of your app. Always test thoroughly, consider the user experience, and strive for clean, maintainable code.Related Articles
- 15 Ways to Attract More Clients to Your Car Rental Company
- Royal Blue Color: Exploring History, Design and Hex Code
- Chargebee Review: Everything You Need to Know Before You Subscribe
- 230+ Merry Christmas Wishes: Heartfelt Greetings and Festive Ideas 2024
- 10+ Best Websites to Watch Cartoons Online for Free
- Tips & Tricks to Choose a Perfect Website Color Scheme
- Top 5 Azure DevOps Integrations for your Business
- How To Integrate Microsoft Outlook With ChatGPT
- How to Add Emoji to Photo: 5 Best Ways To Make Photos Engaging
- How to Get More Clients for Your Event Planning Business
Most Popular Posts
- Work Instruction Essentials for Crafting Clear and Effective Guides
- 21+ Best Brilliant Branding Design Ideas to Spark Creativity
- 17 Best Shopify Alternatives to Consider in 2025
- What are Telegram Music Bots? + [Popular Telegram Integrations]
- 23 Key Advantages of Chatbots for Customers and Businesses