iOS NSNotificationCenter通知中心之多线程

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]);
}

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


线程

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

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

友情链接更多精彩内容