NSNotificationCenter异步通知

2021-04-02  本文已影响0人  懂哲学的老鼠

先说结论:
异步线程发送的Notification,也会在对应的线程中接到通知,并且,对于通知本身是同步执行的

// 发送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    dispatch_queue_t queue = dispatch_queue_create("testQ", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"currentThread1 == %@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"nTest" object:nil];
    });
}
// 接受通知
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(test:)
                                                 name:@"nTest" object:nil];
}

- (void)test:(NSNotification *)noti {
    NSLog(@"currentThread2 == %@",[NSThread currentThread]);
}
打印结果
demo[68642:1059621] currentThread1 == <NSThread: 0x6000036d0a80>{number = 7, name = (null)}
demo[68642:1059621] currentThread2 == <NSThread: 0x6000036d0a80>{number = 7, name = (null)}

同异步测试

- (void)touchesBegan:(NSSet<UITouch *> *)touches
           withEvent:(UIEvent *)event {
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSLog(@"currentThread1 == %@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"nTest" object:nil];
        sleep(3);
        NSLog(@"currentThread2 == %@",[NSThread currentThread]);
    });
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(test:)
                                                 name:@"nTest" object:nil];
}

- (void)test:(NSNotification *)noti {
    NSLog(@"currentThread3 == %@",[NSThread currentThread]);
}
打印结果
注意打印currentThread3与currentThread2,时间上差了3秒
16:38:34.345302+0800 hkzrdemo[70273:1151803] currentThread1 == <NSThread: 0x6000020460c0>{number = 8, name = (null)}
16:38:34.345538+0800 hkzrdemo[70273:1151803] currentThread3 == <NSThread: 0x6000020460c0>{number = 8, name = (null)}
16:38:37.350034+0800 hkzrdemo[70273:1151803] currentThread2 == <NSThread: 0x6000020460c0>{number = 8, name = (null)}
上一篇下一篇

猜你喜欢

热点阅读