前言
在iOS开发中我们回调经常使用delegete、blcok、通知等方式。delegete和blcok都是“一对一”回调,通知可实现“一对多”回调。但是通知有两个明显的弊端:1、不好管理 2、传值只能在userInfo中,这就会导致传值类型不明确等问题。
有什么方式即可以“一对多”回调,又可以明确回调参数类型呢!答案是有的,就是我们今天介绍的GCDMulticastDelegate
1、GCDMulticastDelegate介绍
GitHub上的介绍:GCDMulticastDelegate extracted from XMPPFramework。
GCDMulticastDelegate是从XMPPFramework提取出来的,主要就是为了实现多播委托。
2、GCDMulticastDelegate导入
pod 'GCDMulticastDelegate'
但是如果我们项目中已经
pod 'XMPPFramework'
就无需单独pod 'GCDMulticastDelegate'
了。因为XMPPFramework里面包含了GCDMulticastDelegate。
3、GCDMulticastDelegate使用
3.1、.h文件中
#import <Foundation/Foundation.h>
#import <GCDMulticastDelegate.h>
@protocol HLManagerDelegate<NSObject>
- (void)managerTestMethod;
@end
@interface HLManager : NSObject
{
GCDMulticastDelegate<HLManagerDelegate> *_delegates;
}
+ (instancetype)sharedManager;
/// 添加代理
- (void)addDelegate:(id<HLManagerDelegate>)delegate delegateQueue:(dispatch_queue_t)queue;
/// 删除代理
- (void)removeDelegate:(id<HLManagerDelegate>)delegate;
@end
3.2、.m文件中
#import "HLManager.h"
static HLManager *manager = nil;
static NSObject *g_lock = nil;
@implementation HLManager
+ (instancetype)sharedManager
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[HLManager alloc] init];
});
return manager;
}
- (instancetype)init
{
self = [super init];
if (self) {
_delegates = (GCDMulticastDelegate<HLManagerDelegate> *)[[GCDMulticastDelegate alloc] init];
g_lock = [[NSObject alloc] init];
}
return self;
}
#pragma mark - Public Method
- (void)addDelegate:(id<HLManagerDelegate>)delegate delegateQueue:(dispatch_queue_t)queue
{
@synchronized(g_lock) {
if (!queue) {
queue = dispatch_get_main_queue();
}
[_delegates addDelegate:delegate delegateQueue:queue];
}
}
- (void)removeDelegate:(id<HLManagerDelegate>)delegate
{
if (!delegate) {
return;
}
@synchronized(g_lock) {
[_delegates removeDelegate:delegate];
}
}
@end
3.3、其他类使用HLManagerDelegate
- (void)viewDidLoad {
[super viewDidLoad];
[[HLManager sharedManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
- (void)dealloc {
[[HLManager sharedManager] removeDelegate:self];
}
#pragma mark - HLManagerDelegate
- (void)managerTestMethod
{
NSLog("调用了managerTestMethod方法");
}
4、总结
上面简单演示了GCDMulticastDelegate简单使用。希望对您有帮助!
网友评论