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.
- Use
NotificationCenter
and have the model publish onto it and the VC's subscribe to it - 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. - If you are on iOS13, use
Combine
or (if not) consider usingRxSwift
. Both of these implement theObserver
pattern and can let you do simple publish-subscribes. - 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.
Top comments (0)