NSNotificationCenter通知中心是同步操作还是异步操作

题目

通知中心是同步操作还是异步操作?

代码实现

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    CGFloat x,y,w,h;
    x = 100;
    y = 100;
    w = 100;
    h = 100;

    self.btn.frame = (CGRect){x,y,w,h};
    self.btn.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.btn];

    [self.btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dosth) name:@"click" object:nil];

}
复制代码
- (void)dosth
{
  
    //同步
    NSLog(@"收到通知");
    sleep(3);
    NSLog(@"处理通知完毕");
    
    //异步
    /*
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"收到通知");
        sleep(3);
         NSLog(@"异步-处理通知完毕");
    });
    */
}
复制代码
-(void)btnClick
{
    //同步
    NSLog(@"开始");
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"click" object:nil userInfo:nil]];
    NSLog(@"结束");
    
    //异步
    /*
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
         NSLog(@"异步-开始");
        [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"click" object:nil userInfo:nil]];
         NSLog(@"异步-结束");
    });
     */
}

复制代码

可以在post地方打个断点,会发现通知中心是同步的。

当然也可以做成异步处理。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值