mardi 17 avril 2018

Design Pattern for constructing an object which requires data from multiple UIViewControllers

In this question I want to discuss how to construct an object which requires data from multiple UIViewControllers which are embedded in an UINavigationController.

For this post I'm providing an example where I'm making a demo-app where users can buy fake plane-tickets. This is the oversimplified struct that represents a Ticket:

struct Ticket {

    let originAirport: Airport // UIViewController 1 provides this data.
    let destinationAirport: Airport // UIViewController 1 provides this data.

    let departDate: Date // UIViewController 2 provides this data.
    let returnDate: Date // UIViewController 2 provides this data.

    let customerName: String // UIViewController 3 provides this data.
}

The process of booking a Ticket requires multiple steps / UIViewControllers. In every UIViewController I can get some - but not all data about the ticket. At the end of all steps I want a Ticket struct/object which has all the data in it's properties. What is a nice design pattern to handle this problem?

These are a few "solutions" I considered:

  1. Passing data through segues: For every step / UIViewController I'd pass on a partly constructed Ticket object to the next UIViewController. This new UIViewController adds additional information to the object. The problem with this approach is that for every UIViewController I need to pass a Ticket object with partly filled in information. This means that the properties in Ticket are optional .. which doesn't make sense from the Ticket perspective: all properties are required. The other problem is that the UIViewControllers are tightly coupled with each other and this problem becomes bigger once the amount of steps increase.

  2. Use a Singleton / UserDefaults: This is a hack-ish workaround which isn't a solution to the problem.

Perhaps I'm dealing with an XY problem - maybe my solution doesn't make sense where I'm initialising the Ticket object once all steps are finished. But what would be a good approach to solve this problem?

Aucun commentaire:

Enregistrer un commentaire