Skip to content

Instantly share code, notes, and snippets.

@sc0rch
Created December 31, 2017 13:16
Show Gist options
  • Save sc0rch/5820f59be21bc407b364f355e9b28f3d to your computer and use it in GitHub Desktop.
Save sc0rch/5820f59be21bc407b364f355e9b28f3d to your computer and use it in GitHub Desktop.
/// Useful class if you want your shared instance to have several delegates stored as weak references
public class MulticastDelegate<T> {
private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects()
public func add(delegate: T) {
delegates.add(delegate as AnyObject)
}
public func remove(delegate: T) {
for oneDelegate in delegates.allObjects.reversed() {
if oneDelegate === delegate as AnyObject {
delegates.remove(oneDelegate)
}
}
}
public func invoke(invocation: (T) -> ()) {
for delegate in delegates.allObjects.reversed() {
invocation(delegate as! T)
}
}
}
public func += <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
left.add(delegate: right)
}
public func -= <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
left.remove(delegate: right)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment