iOS StackOverflow Deep Dive: How to get two VC's to talk to each other

loufranco

Lou Franco

Posted on January 27, 2020

iOS StackOverflow Deep Dive: How to get two VC's to talk to each other

This is a new series where I will go into depth on interesting iOS StackOverflow questions:

This one starts out:

What is the most “Swiftian” way of passing a reference between two unrelated ViewControllers (e.g., two ViewControllers that are independently instantiated at different times)?

The gist of the question is that there are two totally unrelated View Controllers that need to show the same information at the same time. The questioner wants to know how they can get references to each other.

My suggestion: Remember that iOS's default architectural pattern is MVC -- or Model-View-Controller. Introducing a model makes this easy.

Now, the default way of doing this (with a delegate) is actually not appropriate because the standard way of implementing that assumes that you have just one, but in this case, we have two (the two VCs).

There are several ways you could go from here.

  1. Use NotificationCenter and have the model publish onto it and the VC's subscribe to it
  2. Use KVO (Key-Value-Observing) on model properties. This is a simple way to go if the model is mostly just properties that change. This is more likely to be the case for simple data, but for this specific problem it probably won't work well. One idea is to have an every increasing Int value, and when you get a KVO update on it, you ask the model for it's current information. The model just does += 1 on it when it updates itself.
  3. If you are on iOS13, use Combine or (if not) consider using RxSwift. Both of these implement the Observer pattern and can let you do simple publish-subscribes.
  4. Going the delegate route is still possible, but it involves an array of delegates -- but you need to implement some kind of array that holds elements weakly. See this: https://www.objc.io/blog/2017/12/28/weak-arrays/. It's more complex than it seems, but possible.

I'll go into more detail in a future article.

💖 💪 🙅 🚩
loufranco
Lou Franco

Posted on January 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related