iOS开发知识小集

iOS中关于NotificationCenter通知线程问题

2019-06-17  本文已影响111人  小熊_07cb
- (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的操作时,需要切入主线程

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

上一篇下一篇

猜你喜欢

热点阅读