I am trying to implement the multicast delegate functionality in Swift. In Objective C, we have this excellent implementation
https://github.com/robbiehanson/XMPPFramework/blob/master/Utilities/GCDMulticastDelegate.m
And I have just created this basic functionality:
protocol MyProtocol : class{
func testString()-> String;
}
class MulticastDelegateNode <T:AnyObject> {
weak var delegate : T?
init(object : T){
self.delegate = object;
}
}
class MulticastDelegate <T:AnyObject> {
var delegates = Array<MulticastDelegateNode<T>>()
func addDelegate(delegate : T){
var newNode = MulticastDelegateNode(object : delegate);
delegates.append(newNode);
}
func removeDelegate(delegate : AnyObject){
self.delegates = self.delegates.filter({ (node : MulticastDelegateNode) -> Bool in
return node.delegate !== delegate;
});
}
}
class OP {
var delegate = MulticastDelegate<MyProtocol>();
func process(){
//...
//make actions
//notify the objects!
}
}
My problem is that it seems I cannot figure out a way to do this:
delegate.testString()
In order to give the command 'testString()' to all delegates that are in the nodes. Can anyone help me with this?
Ok. In some of the solutions I see mistakes (strong retain cycles, race conditions, ...)
Here is what I combine based on 1 day research. For the stack of delegates I used NSHashTable, so all the delegates are having weak reference.
Swift 3.1
How to set delegate:
How to execute function on the delegates: instead of
you use