具有多个控制器的单个代表

cod*_*ner 0 delegates ios swift swift-protocols

我遇到了一个情况,我想用一个委托注册2个不同的UIViewControllers,因为我的项目一次显示2个UIViewControllers.当我触发事件时,我希望两个控制器都得到通知,但不幸的是只有任何一个控制器才能接收到这两个事件.

这是示例代码:

@objc protocol DownloaderDelegate: class {
    func complete()
}

class Downloader {
    static let sharedInstance = Downloader()
    weak var delegate: DownloaderDelegate?

    private init() {

    }

    func downloadFile() {
         self.delegate!.complete()
    }
}
Run Code Online (Sandbox Code Playgroud)

我在UIViewControllers中使用它就像这样:

override viewDidLoad() {
    super.viewDidLoad()

    Downloader.sharedInstance.delegate = self
}
Run Code Online (Sandbox Code Playgroud)

知道如何让视图控制器从单个委托中侦听事件吗?

Jul*_*ere 5

事实上,我认为这里最好的解决方案是从委托模式转移到通知模式(有关Apple文档的更多详细信息:https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia- CocoaCore/Notification.html).

另一个解决方案是用DownloaderDelegate数组替换你的委托.但我真的认为通知解决方案是最干净,最简单的.

这是一篇关于NSNotificationSwift 的好文章:https: //www.andrewcbancroft.com/2014/10/08/fundamentals-of-nsnotificationcenter-in-swift/

编辑: 您应该注意观察员的移除.最简单的方法是在每个类中添加它来监听事件:

deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
}
Run Code Online (Sandbox Code Playgroud)