Just in case that link dies later, here’s what this comment refers to:
class MulticastDelegate <T> {
private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects()
func add(delegate: T) {
delegates.add(delegate as AnyObject)
}
func remove(delegate: T) {
for oneDelegate in delegates.allObjects.reversed() {
if oneDelegate === delegate as AnyObject {
delegates.remove(oneDelegate)
}
}
}
func invoke(invocation: (T) -> ()) {
for delegate in delegates.allObjects.reversed() {
invocation(delegate as! T)
}
}
}
func += <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
left.add(delegate: right)
}
func -= <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
left.remove(delegate: right)
}
Yes, I like this solution too!
The difference between this MulticastDelegate
and MulticastClosureDelegate
shown in this series is that MulticastDelegate
requires that you define a delegate protocol. That’s what <T>
in class MulticastDelegate <T>
is all about.
MulticastClosureDelegate
instead uses closures, so it doesn’t require you to define a delegate protocol.
To which you might wonder, “Which should I use?”
I personally use both! Sometimes, even in the same app.
“When show I use each?”
Another good question-- thanks for being such a good sport.
I usually use MulticastDelegate
for long-lived multicast delegate relationships. Whereas, I use the MulticastClosureDelegate
for short-lived delegate relations (think, “call once and forget about it”).
There’s no reason why you couldn’t use MulticastClosureDelegate
for long-term delegates, however, if you wanted to do it. :]
In that case, it’d likely make more sense to change some of the default parameter values, so the closures won’t automatically get removed (as they do now) by default.
Make sense?
Also, here’s a similar implementation of MulticastDelegate
, which includes comments explaining how it works (for disclosure: I contributed to this):
https://github.com/jonasman/MulticastDelegate/blob/master/Sources/MulticastDelegate.swift
This is what I use in my own projects, and it has a CocoaPod too. :]