美文网首页
线程与通知的那些事儿

线程与通知的那些事儿

作者: 携一两本单色书来 | 来源:发表于2021-07-27 18:30 被阅读0次

    主线程发送,主线程接收

    [[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)}
    

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

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

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

    相关文章

      网友评论

          本文标题:线程与通知的那些事儿

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