Swift语言多播委派 [英] Swift Language Multicast Delegate

查看:123
本文介绍了Swift语言多播委派的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Swift中实现多播委托功能。在目标C中,我们有这个优秀的实现

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()

为了给命令testString()给节点中的所有代理。任何人都可以帮助我这个?

In order to give the command 'testString()' to all delegates that are in the nodes. Can anyone help me with this?

推荐答案

MulticastDelegate的简单演示。

A Simple demo about MulticastDelegate.

class DelegateMulticast <T> {

  private var delegates = [T]()

  func addDelegate(delegate: T) {
    delegates.append(delegate)
  }

  func invokeDelegates(invocation: (T) -> ()) {
    for delegate in delegates {
        invocation(delegate)
    }
  }
}

protocol MyProtocol {
   func testString() -> String
}


class OP {
var delegates = DelegateMulticast<MyProtocol>()

  func process(){
    delegates.invokeDelegates{
        $0.testString()
    }
  }
}

这篇关于Swift语言多播委派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆