Created
December 31, 2017 13:16
-
-
Save sc0rch/5820f59be21bc407b364f355e9b28f3d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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