0

I have 2 ViewControllers, A and B. ViewController A uses sockets and updates its data whenever changes occur.

How can I pass those updated data to ViewController B when it's already presented (programmatically) by A?

I'm thinking to pass ViewController A's update handler class to ViewController B and take advantage of the fact that classes are reference-type, so any change would happen to A's handler, it would also happen to B's. Is it a valid architectural choice?

Sotiris Kaniras
  • 520
  • 1
  • 12
  • 30

1 Answers1

1

You just need to maintain a reference to ViewControllerB in ViewControllerA when you're presenting ViewControllerB in ViewControllerA, here's how:

class ViewControllerA: UIViewController {

    var viewControllerB: ViewControllerB?

    func presentViewControllerB() {
        if let viewControllerB = viewControllerB {
            present(viewControllerB, animated: true)
        } else {
            viewControllerB = ViewControllerB()
            presentViewControllerB()
        }
    }

    func passDataToViewControllerB() {
        viewControllerB?.someData = "Data from ViewControllerA."
    }
}

class ViewControllerB: UIViewController {
    var someData = ""
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • 1
    No issues here (No memory leaks). Since you're planning to present view controller there's already a reference being created. Here you're using the same reference to pass on data. Also, it's a one-way connection, so no reference cycles are occurring here. – Frankenstein Jun 09 '20 at 17:21
  • What if I passed the data with a NotificationCenter observer? – Sotiris Kaniras Jun 09 '20 at 18:59
  • 1
    It's your choice really. There are plenty of methods. – Frankenstein Jun 09 '20 at 19:03