Sharing code between View Controllers

Harry Ng
macOS App Development
2 min readSep 15, 2016

It is quite common that you are building a iOS or macOS application, with several views and view controllers that look very similarly. The legacy way is to copy the code and make the minor changes to create the variations.

I’m sure every developer tried this approach before, and we all know how frustrating it is after making changes to the clones over time.

Refactoring to shared code base

Recently, I have come up with 3 solutions in sharing code between View Controllers.

1. Subclass

This is the learning from the Object-oriented Programming design pattern. For the two view controllers that look like the same, we can first extra the common part and put it in a superclass. Then the two actual view controllers will subclass it to inherit those behaviours.

2. Helper class

The second approach is to create independent class that holds the common behaviors, say sorting a list of content. In general, these methods are self-contained. They could sometimes be defined as static methods. If you want to hold state information, a singleton could work too.

3. Protocol Extension

In Swift, Protocol-oriented Programming (POP) is highly promoted. Protocol in general provides the footprint that a class who implements it should conform to the protocol by providing the method implementation. However, this is just conforming, not sharing code.

Swift takes one step further, in which developer can extend the protocol to provide the method implementation. Thus the ViewController implements the protocol can get advantages of those methods defined in protocol extension.

POP approach

In swift, the 3rd approach using protocol is preferred. However, there are some limitations.

For instance, if you are using #selector() in ViewController like observing NSNotification, the method being called by #selector() should be defined in the ViewController.

Over to you…

I’m sure there are other design patterns that solve this problem. Please let me know if you know a smarter way.

--

--