如何通知从 class 到多个 ViewController 的更改?

How to notify a change from a class to multiple ViewControllers?

我写信是因为我想知道通知从 class 到多个 ViewController 的更改的最佳方法是什么。目前我正在使用委托方法,但我确定这不是用于此目的的最佳方法。我创建了一个 class 接收数据的地方,经过一些处理后,我需要将处理后的消息发送给一些 ViewController s(任何人都显示该消息的一部分。)。目前我有一个 class 的单例,当我通过菜单加载它时,我将其委托分配给另一个 ViewController 。你对做这份工作有什么建议?

这是我的实际代码示例:

import Foundation

protocol MyClassDelegate {

  func receivedData(_ sender: MyClass)

}

class MyClass: NSObject {

  // create the var for delegate
  var delegate: MyClassDelegate?

  // save the single instance
  static private var instance: MyClass {
    return sharedInstance
  }

  private let sharedInstance = MyClass()


  static func getInstance() -> MyClass {
    return instance
  }

  func processData() {

    // at the end of the process
    delegate?.receivedData(self)
  }

}


class Menu: UIViewController {

  private var containerView: UIView!

  private let myClass = Myclass.getInstance()

  private var vcOne = VcOne()
  private var vcTwo = VcTwo()


  override func viewDidLoad() {
    super.viewDidLoad()

    containerView = UIVIew()
    // set containerView position and dimensions
  }

  func selectViewController(previous: UIViewController, next: UIViewController) {

    // remove actual loaded ViewController
    previous.willMove(toParent: nil)
    previous.view.removeFromSuperView()
    previous.removeFromParent()


    // assign the delegate
    myClass.delegate = next

    // add the new ViewController
    self.addChild(next)
    slef.addSubView(next.view)
    next.didMove(toParent: self)
  }

}


class VcOne: UIViewController, MyClassDelegate {

  func receivedData(_ sender: MyClass) {
    // data received
  }
}

class VcTwo: UIViewController, MyClassDelegate {


  func receivedData(_ sender: MyClass) {
    // data received
  }
}

您可以使用 NotificationCenter https://developer.apple.com/documentation/foundation/notificationcenter 广播消息。或使用 KVO。总的来说,我认为通知中心更容易。

简单示例: https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter