线程与通知的那些事儿

主线程发送,主线程接收

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainReceiveMsg:) name:@"mainNote" object:nil];

- (void)mainReceiveMsg:(NSNotification *)x {
    NSLog(@"主线程响应:%@ \n %@", x.userInfo, [NSThread currentThread]);
}

- (IBAction)mainClick:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"mainNote" object:nil userInfo:@{@"name": @"main"}];
    
}

打印日志:

主线程响应:{
    name = main;
} 
 <NSThread: 0x28246c640>{number = 1, name = main}

子线程发送,子线程接收

dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"添加监听:\n %@",  [NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(childReceiveMsg:) name:@"childNote" object:nil];
    });

- (void)childReceiveMsg:(NSNotification *)x {
    NSLog(@"子线程响应:%@\n %@", x.userInfo, [NSThread currentThread]);
}
- (IBAction)childClick:(id)sender {
    dispatch_async(dispatch_queue_create("noteTest", 0), ^{
        NSLog(@"子线程发送:\n %@",  [NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"childNote" object:nil userInfo:@{@"name": @"child"}];
    });
}

打印日志:

添加监听:
 <NSThread: 0x280a07000>{number = 3, name = (null)}
2021-07-27 18:26:03.195074+0800 cs[1153:363345] 子线程发送:
 <NSThread: 0x280a04b00>{number = 5, name = (null)}
2021-07-27 18:26:03.195851+0800 cs[1153:363345] 子线程响应:{
    name = child;
}
 <NSThread: 0x280a04b00>{number = 5, name = (null)}

响应发生在都在发送时的线程

主线程发送,子线程接收:

主线程响应:{
    name = main;
} 
 <NSThread: 0x280bb4640>{number = 1, name = main}
响应执行在主线程

子线程发送,主线程接收:

{
    name = child;
}
 <NSThread: 0x281efdf00>{number = 4, name = (null)}

响应与发送都在发送时所在线程。

可以看到,主线程发送,响应也在主线程
子线程发送,响应在同一线程

所有,在写一些类似下载功能时,一定要将发送通知放在主线程。因为方法可能会被子线程调用。

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

相关阅读更多精彩内容

友情链接更多精彩内容