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
上一篇: 拉条子是啥?怎样做的拉条子才好吃?
下一篇: 排骨汤可以放什么配菜?排骨汤炖多长时间?
推荐阅读