I'm having multiple viewcontrollers (in a navigation stack or maybe not) and each controllers collects some data based on users input. In the end I need to use those data in the last controller.
So what would be the best approach/design-pattern to implement this scenario?
If you have (a navigation stack ) and you need to collect data from all this view controllers
the best way Not to use User-defaults , or Singleton
for your case you have to do container of view controllers to handle particular Process . Note (UINavigationController
, UITabBarController
, and UISplitViewController
* is just containers)
For example create account that require 4 steps that collect users inputs , each step is represented by ViewController and at end you need to push all this data to API server ,
So create Parent ContainerViewController of child viewControllers and use Delegation
to pass data after every step to ParentViewController
, ParentViewController will be leader to allow next step and provide Data for this step . Here is how to begin create Your own Container managing-view-controllers-with-container
Do not use a Singleton
Singletons can be accessed directly from anywhere in the app. You have no control. a-lot coupling in your code and make your objects hard to test in the future
Do not use UserDefaults
UserDefaults is to store user preferences that persist between app executions.Anything stored there will stay until you remove, so it is not a mechanism to pass data between objects.
So you have to use architecture pattern in the future
Architecture
Each ViewController should only take care of their own screen . also viewController shouldn't know about each other. if we do this we will remove a-lot of coupling between our view controller classes.
So You can use Coordniator to be The leader that handle all navigation Coordniator
and check how to Integrate with MVVM at MVVM-C
also Viper use this technique to handle navigation check Viper