iOS中关于NotificationCenter通知线程问题

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"测试类";
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(xxx) name:@"xxx" object:nil];
        NSLog(@"子线程注册通知===%@",[NSThread currentThread]);
    });
    NSLog(@"主线程===%@",[NSThread currentThread]);
    
    UIButton *sendBtn=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
      sendBtn.backgroundColor=[UIColor redColor];
    [sendBtn setTitle:@"发送通知" forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendNoti) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];

    // Do any additional setup after loading the view.
}
-(void)sendNoti
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"xxx" object:nil];
        NSLog(@"发送通知子线线程===%@",[NSThread currentThread]);
    });
}
-(void)xxx
{
    NSLog(@"收到通知线程===%@",[NSThread currentThread]);
}

打印结果:
1、子线程注册 子线程发送

主线程===<NSThread: 0x283f89a00>{number = 1, name = main}
子线程注册通知===<NSThread: 0x283fd9140>{number = 3, name = (null)}
收到通知线程===<NSThread: 0x283fdae80>{number = 4, name = (null)}
发送通知子线线程===<NSThread: 0x283fdae80>{number = 4, name = (null)}

2、主线程注册 子线程发送

 主线程注册通知===<NSThread: 0x281a95a40>{number = 1, name = main}
 收到通知线程===<NSThread: 0x281ac1640>{number = 3, name = (null)}
 发送通知子线线程===<NSThread: 0x281ac1640>{number = 3, name = (null)}

结论:
不管你在哪个线程注册通知,发送通知在哪个线程,接受通知处理方法就会在哪个线程,即发送通知和接受通知在同一个线程,因此,若要更新UI的操作时,需要切入主线程

注意:通知触发的方法是同步执行,所以通知会有延迟

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容