iOS 之 MulticastDelegate

前段时间在研究XMPPFramework的时候发现了里面一个很有趣的特性,MulticastDelegate,也就是多重代理。我们知道iOS开发中对象直接常用的沟通方式一般分为BlockDelegateNotification 其中只有Notification是一对多的,而DelegateBlock都是一对一的。XMPPFramework中对于 MulticastDelegate的解释如下:

The xmpp framework needs to support an unlimited number of extensions. This includes the official extensions that ship with the framework, as well as any number of extensions or custom code you may want to plug into the framework. So the traditional delegate pattern simply won't work. XMPP modules and extensions need to be separated into their own separate classes, yet each of these classes needs to receive delegate methods. And the standard NSNotification architecture won't work either because some of these delegates require a return variable. (Plus it's really annoying to extract parameters from a notification's userInfo dictionary.)

简单来说就是XMPPFramework需要支持很多的扩展功能,而且这些扩展功能是可以共存的,XMPPFramework 的 Module 需要区分这些扩展,同时这些扩展的代理需要一个返回值,所以也不能用通知,最终使用了多重代理。

XMPPFramework怎么说


XMPPFramework中对MulticastDelegate的具体说明分为了以下几点

delegates and notifications

主要说明了代理和通知各自的利弊

| 代理 | 通知
-------------|-------------|-------------
优点 | 大量回调方法是书写方便

回调参数读写方便

允许返回值| 允许一对多传值
缺点 | 只能一对一传值

| 回调较多时注册繁琐

从userInfo中去除参数繁琐

不允许返回值

What are the requirements for XMPPFramework?

1.XMPPFramework需要一对多广播消息的的能力
2.方便扩展
3.允许返回值
4.线程安全(Socket IO, xml解析, disk IO等)

What's it look like?

客户端使用MulticastDelegate的方式如下

// Add myself as a delegate, and tell xmppStream to invoke my delegate methods on the main thread
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];

// Then just implement whatever delegate methods you need like normal
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
   ...
}

What about return variables?

我们有如下代理方法

- (BOOL)worker:(Worker *)sender shouldPerformSubTask:(id)subtask;

如果有三个对象都实现了这个代理,其中两个返回 YES,一个返回 NO,我们应该根据不同的情况做不同处理,比如在这里,我们处理为只要有一个代理返回NO,那么我们就不执行subtask
那么问题就来了:我们该如何实现这种代理逻辑呢?

GCDMulticastDelegate中的每一个节点都保存有一个delegate和一个dispatch_queue,但是我们并不能只是简单的遍历GCDMulticastDelegate中的节点,原因如下:

假设我们的对象运行在dispatch_queue_a, delegate运行在 dispatch_queue_b,而我们使用dispatch_sync(dispatch_queue_b, block),同时在block中使用了当前对象的一些属性,那么就会形成死锁。

处理返回值的 MulticastDelegate 实现举例:
// Delegate rules:
// 
// 如果有任意一个代理返回NO,则result为NO
// 否则result为YES.

SEL selector = @selector(worker:shouldPerformSubTask:);

NSUInteger delegateCount = [multicastDelegate countForSelector:selector];
if (delegateCount == 0)
{
    // 没有代理实现该方法的时候默认为YES
    [self continuePerformSubTask:YES];
}
else
{
    // 查询代理
    GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator];

    dispatch_semaphore_t delSemaphore = dispatch_semaphore_create(0);
    dispatch_group_t delGroup = dispatch_group_create();

    id del;
    dispatch_queue_t dq;

    while ([delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector])
    {
        dispatch_group_async(delGroup, dq, ^{ @autoreleasepool {

            if (![del worker:self shouldPerformSubTask:subtask])
            {
                dispatch_semaphore_signal(delSemaphore);
            }
        }});
    }

    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(concurrentQueue, ^{ @autoreleasepool {

        // 等待代理执行结束
        dispatch_group_wait(delGroup, DISPATCH_TIME_FOREVER);

        BOOL shouldPerformSubTask = (dispatch_semaphore_wait(delSemaphore, DISPATCH_TIME_NOW) != 0);

        dispatch_async(ourQueue, ^{ @autoreleasepool {
            [self continuePerformSubTask:shouldPerformSubTask];
        }});

        dispatch_release(delSemaphore);
        dispatch_release(delGroup);
    }});
}

GCDMulticastDelegate


上面示例中提到了GCDMulticastDelegate,也就是多重代理的核心实现类, XMPPFramework的源码中可以看到GCDMulticastDelegate包含分为以下几部分:

  • GCDMulticastDelegateNode
  • GCDMulticastDelegateEnumerator
  • GCDMulticastDelegate

GCDMulticastDelegateNode表示代理数组中的节点,里面包括一个代理对象 id delegate 和一个执行代理需要的现成 dispatch_queue_t delegateQueue

GCDMulticastDelegateEnumerator,用于对当前的代理数组进行枚举操作,属性有 代理数组 delegateNodes, 当前遍历的节点下标currentNodeIndex,代理数组总数 numNodes

GCDMulticastDelegate 主要实现了对于代理数组的增删操作已经特殊的统计操作如:

//返回某个各项遵循代理的数量
- (NSUInteger)countOfClass:(Class)aClass
{
 NSUInteger count = 0;
 
 for (GCDMulticastDelegateNode *node in delegateNodes)
 {
  id nodeDelegate = node.delegate;
  #if __has_feature(objc_arc_weak) && !TARGET_OS_IPHONE
  if (nodeDelegate == [NSNull null])
   nodeDelegate = node.unsafeDelegate;
  #endif
  
  if ([nodeDelegate isKindOfClass:aClass])
  {
   count++;
  }
 }
 
 return count;
}
//返回实现了某个选择子的代理的数量
- (NSUInteger)countForSelector:(SEL)aSelector
{
 NSUInteger count = 0;
 
 for (GCDMulticastDelegateNode *node in delegateNodes)
 {
  id nodeDelegate = node.delegate;
  #if __has_feature(objc_arc_weak) && !TARGET_OS_IPHONE
  if (nodeDelegate == [NSNull null])
   nodeDelegate = node.unsafeDelegate;
  #endif
  
  if ([nodeDelegate respondsToSelector:aSelector])
  {
   count++;
  }
 }
 
 return count;
}

综上所述,当我们遇到对象一对多传值,同时需要一个返回值的时候就可以使用MulticastDelegate

你可能感兴趣的:(iOS 之 MulticastDelegate)