objective-c - 多个类使用委托(delegate)的设计模式

标签 objective-c swift design-patterns delegates protocols

我想通过委托(delegate)方法将数据从一个类发送到其他类。但是我发现一个问题,对于每个需要监听数据更改的类,我必须为它们创建一个单独的委托(delegate)协议(protocol)。

protocol MainDelegateForA {
  func mainResultObtained(result: String)
}

protocol MainDelegateForB {
  func mainResultObtained(result: String)
}

class MainViewController: UIViewController {

  var delegateForA: MainDelegateForA?
  var delegateForB: MainDelegateForB?

  override func viewDidLoad() {
    let subscribingViewA = SubscribingViewA()
    delegateForA = subscribingViewA
    let subscribingViewB = SubscribingViewB()
    delegateForB = subscribingViewB
    distributeResult("Calculation obtained!!!")
  }

  func distributeResult(result: String) {
    delegateForA?.mainResultObtained(result)
    delegateForB?.mainResultObtained(result)
  }

}

class SubscribingViewA: MainDelegateForA {

  func mainResultObtained(result: String) {
    print("SubscribingViewA got result:\(result)")
  }

}

class SubscribingViewB: MainDelegateForB {

  func mainResultObtained(result: String) {
    print("SubscribingViewA got result:\(result)")
  }

}

上面的代码是我的意思的一个过于简化的版本。

当然是

keeping a reference of each class and send the result via directly calling a public method of the class

Using notification and make every class that needs the changes to listen to the data change

可能是解决方案之一,但是

i want to write this very particularly using the delegation method

如果可能的话,我是否可以在不为每个类使用单独的协议(protocol)的情况下实现此目的?

最佳答案

正如luk2302所指出的,您可以使用委托(delegate)数组来实现它:

var delegates = [MainDelegate]()

那么你只需要使用一个循环(也许它可以在swift中简化):

for delegate in self.delegates {
    delegate.mainResultObtained(result)
}

关于objective-c - 多个类使用委托(delegate)的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37294468/

相关文章:

ios - 如何使用动画 iOS 显示模态视图?

ios - 取消选择 Segment 的默认值

iOS 二进制数据列未显示在 Sqlite 数据库中?

ios - Swift 和 Socket.io : Event doesn't run anymore when re-open a controller

asp.net - 业务逻辑在MVC模式中属于什么位置

security - Node.js 应用程序的授权方法和设计模式

ios - 在启动时显示自定义键盘

ios - 如何从纯 C 函数获取返回值到 swift?

ios - 在 swift3 中加载 webview 时后退按钮卡住了?

c# - 洋葱架构的 DDD 限界上下文