我想通过委托(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/