欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Notifycation

程序员文章站 2022-04-17 09:02:27
1. 类A 抛出消息[[NSNotificationCenter defaultCenter] postNotificationName:@"USB_DISCONNECTED" object:str];-(void)register{ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 2.通过异步函数将将任务加入队列 dispatc....

1. 类A 抛出消息

 [[NSNotificationCenter defaultCenter] postNotificationName:@"USB_DISCONNECTED" object:str];

-(void)register{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 2.通过异步函数将将任务加入队列
    dispatch_async(queue, ^{
        for(int i = 0 ;i <= 20; ++i){
        [NSThread sleepForTimeInterval:1];
            NSString * str = [NSString stringWithFormat:@"%d",i];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"USB_DISCONNECTED" object:str];
        }
    });
}

2.类B 监听

//初始化
-(void)initNotifi
{
    [[MiUtil sharedInstance]register];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) name:nil object:nil];
}
//销毁监听

-(void)destroyNotify{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"USB_DISCONNECTED" object:nil];
}

//监听回调  [notification object] 是传的参数
-(void)notificationHandler:(NSNotification*)notification{
    if([notification.name compare:@"USB_CONNECTED"]==NSOrderedSame){
  
    }else if([notification.name compare:@"USB_DISCONNECTED"]==NSOrderedSame){
            NSLog(@"%@",[notification object]);
        
    }
}

name设置成nil是监听所有
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) name:@"USB_DISCONNECTED" object:nil];

[notification object]是参数

 

本文地址:https://blog.csdn.net/yonggandess/article/details/109612755

相关标签: ObjectC