美文网首页工作生活
iOS NSNotificationCenter通知中心之多线程

iOS NSNotificationCenter通知中心之多线程

作者: 不会写代码的尬先生 | 来源:发表于2019-07-01 18:30 被阅读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]);
}

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


线程

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

相关文章

网友评论

    本文标题:iOS NSNotificationCenter通知中心之多线程

    本文链接:https://www.haomeiwen.com/subject/jfsncctx.html