Battle of the iOS Architecture Patterns: Model View Presenter with Coordinators (MVP-C)

Radu Dan
Geek Culture
Published in
9 min readJul 7, 2021
Architecture Series — Model View Presenter with Coordinators (MVP-C)

Motivation

Before starting to develop an iOS app, we have to think of the structure of the project. We need to consider how we add those pieces of code together so they make sense later on — when we come back and revisit a part of the app — and how to form a known “language” with the other developers.

If you missed the other articles, you can access them below or you can find the links at the end of this post.

We are going to explore how we can simplify navigation, by introducing the Coordinator pattern to our code.
As usual, we will see how we apply the pattern to each screen, seeing the actual implementation and the source code. At the end, we will show the build times and detail some key observations about MVP with Coordinators, compared to the other architecture patterns.

If you just want to see the code, feel free to skip this post. The code is available open source on GitHub.

Why an Architecture Pattern for Your iOS App?

The most important thing to consider is to have an app that can be maintainable. You know the view goes there, that this view controller should do X and not Y. And more important, others know that too.

Here are some advantages of choosing a good architecture pattern:

  • Easier to maintain
  • Easier to test the business logic
  • Develop a common language with the other teammates
  • Separate the responsibility of your entities
  • Fewer bugs

Defining the Requirements

Given an iOS application with six or seven screens, we are going to develop it using the most popular architecture patterns from the iOS world: MVC, MVVM, MVP, VIPER, VIP, and Coordinators.

The demo app is called Football Gather and is a simple way for friends to track the scores of their amateur football matches.

Main features

Ability to:

  • Add players in the app
  • Assign teams to the players
  • Edit players
  • Set a countdown timer for matches

Screen mockups

Screen mockups of “Football Gather”, the iOS app

Backend

The app is powered by a web app developed in the Vapor web framework. You can check out the app in my Vapor 3 initial article and the article about Migrating to Vapor 4.

What are Coordinators

The concept of Coordinators was first brought by Soroush Khanlou, in 2015, as a solution for handling the flow logic in view controllers.

As your app grows in size and complexity, you might need to reuse some of the view controllers in new places, and by coupling the flow logic in the view controller is hard to achieve that. To execute the pattern well, you will need one high-level or base coordinator that directs the whole application, as Soroush states.

There are a few benefits of extract the flow into a coordinator:

  • View controllers can focus on their main goal, depending in what architecture pattern are you using in your app (binding a model to a view, for example).
  • The initialisation of view controllers is extracted in a different layer.

Solving problems with coordinators:

  • Overstuffed app delegates: we tend to add a lot of stuff into our app delegate, and with the use of a base app coordinator we can move some of our code over there.
  • Too many responsibilities: view controllers tend to do a lot of stuff, especially in an MVC architecture (model binding, view handling, data fetching, data transformation, etc).
  • Smooth flow: navigation flow now is moved out of the view controller and added in a coordinator.

You start with the app coordinator, solving the problem of doing so many things in the AppDelegate.
Here you can allocate the window object, create your navigation controller and initialise the first view controller. In Martin Fowler’s - Patterns of Enterprise Application Architecture is called the Application Controller.

A rule of coordinators is that every coordinator holds an array of its child coordinators. In this way, we prevent the child coordinators from being deallocated.
If you have a tab bar app, each navigation controller has its own coordinator. Each coordinator is allocated by its parent coordinator.

Besides the flow logic, the coordinator also takes the responsibility from the view controllers of model mutation.

Advantages

  • Each view controller is now isolated.
  • View controller are reusable.
  • Every task and sub-task in your app has a dedicated way of being encapsulated.
  • Coordinators separate display-binding from side effects.
  • Coordinators are objects fully in your control.

The back problem

What happens when the navigation controller navigates back in the stack? For that special bar button item, we don’t have much control over it. We can write our own custom back button, but what happens when the user swipes right to go back?

One way of solving this problem is to keep a reference of the coordinator inside the view controller and call its didFinish method in viewDidDisappear. This is fine for a simple app, but we won’t solve the problem when we have, for example, multiple view controllers shown in the child coordinator.

As Soroush mentions, we can implement UINavigationControllerDelegate to get access to these kind of events.

  1. Implement the UINavigationControllerDelegate in your main app coordinator.
    We are interested in the instance method navigationController:didShowViewController:animated:, which is called just after the navigation controller displays a view controller’s view and navigation item properties.
    When you get a triggered event that a view controller has been popped from the view stack, you can deallocate the relevant coordinators.
  2. Subclass UIViewController and make your it part of your flow.
    In this special subclass you will have a dictionary that keeps the entries of your coordinators:
    private var viewControllersToChildCoordinators: [UIViewController: Coordinator] = [:]
    You implement the UINavigationControllerDelegate in this class. When a view controller is popped and is part of the dictionary, it will be removed and deallocated.
    The downside and main tradeoff with this approach is that your special subclass (which is a UIViewController) does more than we want.

Applying to our code

We start first with defining our application coordinators:

The start function takes care of allocating the view controller and pushing it into the navigation controller stack.

We define a Coordinatable project that our view controllers will implement, so they can delegate to their coordinator specific navigation tasks (such as going back).

Next, we create our main app coordinator: AppCoordinator and initialise it within the AppDelegate.

The AppDelegate now looks like this:

Our first screen is Login. We do the following adjustments so it can support coordinators:

LoginCoordinator

The LoginCoordinator is presented below:

An alternative to Coordinatable, is to use delegation i.e. create a LoginViewControllerDelegate that contains the method navigateToPlayerList, and make LoginCoordinator the delegate of this class.

And the final piece for LoginScreen, is to remove the segues from the storyboard.

Simplified version of the Main.storyboard

As we are going to instantiate all of our view controllers from the storyboard, let’s define a convenient method to do that:

We now can allocate a view controller by setting the storyboard ID in the designated storyboard and use:

PlayerList screen suffers the following adjustments:

  • We removed PlayerListTogglable, the pop functionality resides completely in the responsibilities of Coordinators.
  • Make it implement Coordinatable so we can have a reference to the View Controller’s coordinator.
  • Remove the delegate methods from PlayerDetailViewControllerDelegate, AddPlayerDelegate and PlayerListTogglable.
  • Enhance the public API with the methods that will be required after a player is edited (reload data), added and after a gather finishes (toggleViewState).

To navigate to different screens from PlayerList (to Add or Edit screens, for example), we created the appropriate segue identifier in the Presenter and forward it to the ViewController using the View layer. We now deprecated the use of segue identifiers, all routing will be done using Coordinators. So, let’s implement these changes:

PlayerListCoordinator

The coordinator implementation is presented below:

There are quite a few changes we had to do to PlayerEdit and PlayerDetail screens.

Firstly, we had to make them implement Coordinatable, so we can have a reference to the coordinators, same as we did for PlayerList.

In PlayerDetails, we had to make setupTitle method public, because when we edit a player and change its name, we will need to communicate this change to the ViewController so it can refresh the navigation title. The title is actually the player name.

Same thing we did to reloadData(), and created a new function updateData(player) to communicate to the View the player changes.

We use PlayerDetailViewDelegate to listen to changes that happen in the View layer:

PlayerDetailViewDelegate has now changed the simple didRequestEditView method, into the one that you see above.
This is called from didSelectRow table view's delegate:

PlayerDetailCoordinator

Full code below:

PlayerEditCoordinator

The implementation is pretty straightforward:

PlayerAddCoordinator

The add players feature is impacted a little, because it’s very simple. The coordinator looks like this:

In PlayerAddViewController, we modify didAddPlayer (that is called from the View layer) as presented below:

ConfirmPlayersCoordinator

In ConfirmPlayers, we take in the selected players dictionary, we choose a team for them and finally we start the gather.

ConfirmPlayersCoordinator looks like this:

In ConfirmPlayersView we changed the method didStartGather() and passed the GatherModel in the parameter list: func didStartGather(_ gather: GatherModel).

GatherCoordinator

Finally, GatherCoordinator is detailed below:

GatherViewController’s didEndGather method has reduced considerably from:

To:

Key Metrics

Lines of code — Coordinators

Lines of code — View Controllers

Lines of code — Views

Lines of code — Presenters

Lines of code — Local Models

Unit Tests

Build Times

Tests were run in iPhone 8 Simulator, with iOS 14.4, using Xcode 12.5.1 and on an i9 MacBook Pro 2019.

Conclusion

Another one bites the dust. Congrats! We have finished another Architecture Series implementation article.

We discovered together how we can implement the Coordinator pattern to an existing application, simplifying the View Controllers.

Firstly, we had to take off all segues from the storyboards, leaving some hanging screens there. If we would open again the Main.storyboard we wouldn't know how the screens are connected. We can find that somehow from how the view controllers are positioned, but this isn't very intuitive in all cases.

Then, we introduced some new classes at the Application level to create the main coordinator.

Next, we took module by module and applied the new pattern, simplifying how things are passed between the screens and how we initiate the next step in our journey. We no longer need to perform segues, hold a reference in the Presenter of the Model and when the View Controller is prepared to perform the segue to go way back to the Presenter (or hold a reference in the ViewController) to retrieve the Model we need for the next screen.

Finally, we implemented the Delegation pattern to communicate from child to parent coordinators (e.g. adding or editing players communicating back to the player list to refresh the screen).

I think this is a great pattern and can be used in all apps that want to move away from segues and Storyboards.

By looking at the number of lines of code, we have introduced 348 new lines.

However, we now have 64 LOC less in the view controllers.

As we can see in LoginViewController we increased the LOC with three. Quite unusual...why is that?!

Well, view controller is simple and it had just some one liners when performing the segues. When adopting the Coordinator pattern we introduced two new variables:

weak var coordinator: Coordinator?private var listCoordinator: PlayerListCoordinator? {
coordinator as? PlayerListCoordinator
}

The Views and the Presenters have kept mostly the same number of LOC.
Some small difference in the PlayerDetail module, where we introduced 3 new LOC in PlayerDetailView, because we introduced three new variables to be passed to the Edit screen (see didSelectRowAt method). However, we managed to remove 7 LOC from PlayerListPresenter.

So, as expected, the main beneficiaries of this pattern are the View Controllers.

The build times have increased a little, probably because we have introduced new files and the compiler needs to do more stuff. Each time we are doing a clean build and wiping the Derived Data folder, we loose almost 2 seconds compared to the app coded in MVP without Coordinators and more than 5 seconds when the app was using MVC.

This is not catastrophic, we usually use a CI solution for this and we don’t need to wait locally to have all tests green.

And that’s a wrap!

Useful Links

--

--