codelearner codelearner - 7 months ago 19
Swift Question

Single delegate with multiple controllers

I ran into a situation where I want to register 2 different UIViewControllers with one delegate, because my project is showing 2 UIViewControllers at a time. When I trigger the event, I want both the controllers to get notified, but unfortunately only either controller can receive the event not both.

Here is sample code:

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

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

private init() {

}

func downloadFile() {
self.delegate!.complete()
}
}


I am then using it like this in both UIViewControllers:

override viewDidLoad() {
super.viewDidLoad()

Downloader.sharedInstance.delegate = self
}


Any idea how to make both the view controllers to listen to event from single delegate?

Answer

In fact, I think the best solution here would be to move from the delegate pattern to the Notification Pattern (more details on Apple's documentation: https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Notification.html ).

Another solution would be to replace your delegate by an array of DownloaderDelegate. But I truly think that the Notifications solution is the cleanest and simplest.

Here is a good article on NSNotification in Swift: https://www.andrewcbancroft.com/2014/10/08/fundamentals-of-nsnotificationcenter-in-swift/

Edit: You should take care of observers removal. The simplest way to do so is to add this in each class listening for events:

deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
}