I have the need to maintain a set of weak references (delegates) so that any currently alive referrence gets notified when some event happens. I picked up a technique posted somwhere on the web, whereby you keep an array of structures where the structure contains a single weak reference:
private struct WeakThing<T: AnyObject> {
weak var value: T?
init (value: T) {
self.value = value
}
}I declare a protocol (which in 7b4 now must be @objc):
@objc protocol UserWatcher: AnyObject {
func userUpdated(user: User)
}
final class User: NSObject {
private var watchers = [WeakThing<UserWatcher>]()
...The watchers are used here:
for wo in watchers {
if let delegate = wo.value {
dispatch_async(dispatch_get_main_queue()) {
delegate.userUpdated(self)
}
}Not shown is (future) code to remove the WeakThing structure if the value has gone to nil.
Is there a better way to do this?