Delegate - 高级用法之多播委托

  • iOS多播Delegate类——GCDMulticastDelegate用法小结

  • iOS 多播委托(GCDMulticastDelegate)

在IOS中我就以我们平常用的最多的delagate为例,普通的delegate只能是一对一的回调,无法做到一对多的回调。而多播委托正式对delegate的一种扩展和延伸,多了一个注册和取消注册的过程,任何需要回调的对象都必须先注册。

如何在IOS中实现多播委托?老外早就已经写好了,而且相当的好用。我最初接触IOS多播委托是我在研究XMPPframework的时候,而多播委托可以说是XMPPframework架构的核心之一。具体的类名就是GCDMulticastDelegate,从名字就可以看出,这是一个支持多线程的多播委托。那为什么要支持多线程呢?我的理解是多个回调有可能不是在同一个线程的,比如我注册回调的时候是在后台线程,但是你回调的时候却在UI线程,那就有可能出问题了。因此必须保证你注册的时候在哪个线程上注册的,那么回调的时候必须还是在那个线程上回调的。

GCDMulticastDelegate库

#import "ViewController.h"
#import "MulticastDelegateBaseObject.h"

//继承自多播委托基类的userInfo类
@interface UserInfo : MulticastDelegateBaseObject

@property (nonatomic,strong)NSString *userName;

@end

@implementation UserInfo
-(void)setUserName:(NSString *)userName{
    _userName=userName;
    [multicastDelegate setText:userName];//调用多播委托
}
@end


@interface ViewController (){
    UserInfo *userInfo;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //初始化一个userinfo的实例
    userInfo=[[UserInfo alloc] init];
    
    //添加一个lable
    UILabel *lable =[[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 30)];
    lable.backgroundColor=[UIColor blueColor];
    lable.textColor=[UIColor blackColor];
    [userInfo addDelegate:lable delegateQueue:dispatch_get_main_queue()];//向多播委托注册
    [self.view addSubview:lable];
    
    lable =[[UILabel alloc] initWithFrame:CGRectMake(0, 60, 100, 30)];
    lable.backgroundColor=[UIColor blueColor];
    lable.textColor=[UIColor blackColor];
    [userInfo addDelegate:lable delegateQueue:dispatch_get_main_queue()];
    [self.view addSubview:lable];
    
    lable =[[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 30)];
    lable.backgroundColor=[UIColor blueColor];
    lable.textColor=[UIColor blackColor];
    [userInfo addDelegate:lable delegateQueue:dispatch_get_main_queue()];
    [self.view addSubview:lable];
    
    //添加一个按钮
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(200, 20, 100, 50)];
    [btn setBackgroundColor:[UIColor blueColor]];
    [btn setTitle:@"button1" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnCLicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
}

-(void)btnCLicked:(UIButton *)btn{
    userInfo.userName=@"123456";//给userInfo赋值
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(Delegate - 高级用法之多播委托)