NSNotificationCenter异步通知

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

// 发送通知
- (void)touchesBegan:(NSSet *)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 == {number = 7, name = (null)}
demo[68642:1059621] currentThread2 == {number = 7, name = (null)}

同异步测试

- (void)touchesBegan:(NSSet *)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 == {number = 8, name = (null)}
16:38:34.345538+0800 hkzrdemo[70273:1151803] currentThread3 == {number = 8, name = (null)}
16:38:37.350034+0800 hkzrdemo[70273:1151803] currentThread2 == {number = 8, name = (null)}

你可能感兴趣的:(NSNotificationCenter异步通知)