线程与通知的那些事儿

主线程发送,主线程接收

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

打印日志:

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

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

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

主线程响应:{
    name = main;
} 
 {number = 1, name = main}
响应执行在主线程

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

{
    name = child;
}
 {number = 4, name = (null)}

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

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

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

你可能感兴趣的:(线程与通知的那些事儿)