工作生活

iOS NSNotificationCenter通知中心之多线程

2019-07-01  本文已影响0人  不会写代码的尬先生

1、主线程监听,子线程发通知

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    NSLog(@"1");
    dispatch_queue_t queue = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSLog(@"serial %@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil];

    });
    NSLog(@"2");
}

- (void)receive{
    NSLog(@"receive %@",[NSThread currentThread]);
}

在主线程监听,子线程发通知,会在子线程接收到通知。


多线程

2、子线程监听,子线程发通知

- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"global%@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    NSLog(@"1");
    dispatch_queue_t queue = dispatch_queue_create("serial", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"serial %@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil];

    });
    NSLog(@"2");
}

- (void)receive{
    NSLog(@"receive %@",[NSThread currentThread]);
}

子线程监听,子线程发通知,会在发通知的线程里接收到消息


线程

3、子线程监听,主线程发通知

- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"global%@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    NSLog(@"1");
    NSLog(@"serial %@",[NSThread currentThread]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil];
    NSLog(@"2");
}

- (void)receive{
    NSLog(@"receive %@",[NSThread currentThread]);
}

子线程监听,主线程发通知,会在主线程接收到消息.


线程

总结:接收通知和发送通知时所在线程一致,和监听时所在线程无关。

上一篇 下一篇

猜你喜欢

热点阅读