Updated 25 August 2021
Multicast Delegate is a generic wrapper around yet another delegate protocol, that means it create one-to-many delegate relationships. This allows providing an object with an array of delegates. NotificationCenter also doing same thing but main difference are eliminates all opportunities for testing and Not type-safe in any way. Thats NotificationCenter not a good choice for manage states.
First,create MulticastDelegate class.
1 2 3 4 5 |
final class MulticastDelegate<T> { private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects() } |
MulticastDelegate is a utility class that keeps track of delegates in an array and invokes arbitrary blocks of code on them. And to avoid retain cycles, we chose NSHashTable to hold weak references to delegates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
extension MulticastDelegate { func add(_ delegate: T) { delegates.add(delegate as AnyObject) } func remove(_ delegateToRemove: T) { for delegate in delegates.allObjects.reversed() { if delegate === delegateToRemove as AnyObject { delegates.remove(delegate) } } } func invoke(_ invocation: (T) -> Void) { for delegate in delegates.allObjects.reversed() { invocation(delegate as! T) } } } |
Now we have added methods thats manages multiple delegates.
Now, We will use this delegate in our main class.
1 2 3 4 5 6 7 8 9 10 11 12 |
@objc protocol DataPassProtocal : NSObjectProtocol { func dataPass() } class MyClass { var multicastDelegate: MulticastDelegate<DataPassProtocal> = .init() func callDelegates() { multicastDelegate.invoke { $0.dataPass() } } } |
I hope this code will help you better to understand Multicast Delegate in Swift. If you feel any doubt or query please comment below.
Thanks for the read this blog and if you want to visit my other blog click here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.