通知在多线程中的使用

1)通知的基本使用

@property (nonatomic, weak) id observe;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //监听通知(一定要先监听再发出通知, 否则监听不到通知)
    //方式一
    //Observer:观察者
    //selector:只要一监听到通知,就会调用观察者这个方法
    //name:通知名称
    //object:谁发出的通知
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveNote) name:@"note" object:nil];
    //方式二
    //name:通知名称
    //object:谁发出的通知
    //queue:决定block在哪个线程执行,nil:在发布通知的线程中执行
    //usingBlock:只要监听到通知,就会执行这个block
    // 注意:一定要记得移除
    _observe = [[NSNotificationCenter defaultCenter] addObserverForName:@"note" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        //只要监听到通知,就会调用
        NSLog(@"%@",[NSThread currentThread]);
        NSLog(@"%@",self);
    }];
    //发出通知
    //name:通知名称
    //object:谁发出的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"note" object:nil];
}
//移除通知
//一个对象即将销毁就会调用
// - (void)dealloc {
//     //移除通知
//     [[NSNotificationCenter defaultCenter] removeObserver:self];
//}
- (void)dealloc {
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:_observe];
}
//监听到通知就会调用
//- (void)reciveNote {   
//    NSLog(@"接收到通知");
//}

2)通知在多线程中的使用

//方式一
//异步:监听通知,主线程:发出通知
- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 异步任务
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveNote) name:@"note" object:nil];
    });
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {                    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"note" object:nil];
}
// 监听到通知就会调用
// 异步:监听通知,主线程:发出通知,接收通知代码在主线程
// 主线程:监听通知,异步:发出通知,接收通知代码在异步
// 总结:接收通知代码由发出通知线程决定
- (void)reciveNote
{
    //dispatch_sync(dispatch_get_main_queue(), ^{
    //   //更新UI      
    //});
    NSLog(@"%@",[NSThread currentThread]);
    NSLog(@"接收到通知");   
}
//方式二
- (void)test2
{
    //queue:决定block在哪个线程执行,nil:在发布通知的线程中执行
    //[NSOperationQueue mainQueue]:一般都是使用主队列
    _observe = [[NSNotificationCenter defaultCenter] addObserverForName:@"note" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        NSLog(@"%@",[NSThread currentThread]);
        NSLog(@"%@",self);     
    }];
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值