addObserver 在主线程中使用 GCD 并在全局线程中使用 post 通知,但永远不会调用该方法

addObserver in main thread using GCD and post notification in a global thread but the method never be called

- (void)viewDidLoad {
    [super viewDidLoad];
    //NSNotificationCenter第一坑

    NSLog(@"current thread:%@",[NSThread currentThread]);

    //在主线程中注册通知并转发消息
    //add observer in main thread and deal in main thread

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"current thread:%@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"notificaiton_1" object:nil];
    });

    //在子线程中发送通知
    //post notification in another thread not in the same thread as main

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [[NSNotificationCenter defaultCenter] postNotificationName:@"notificaiton_1" object:nil];

    });


    // Do any additional setup after loading the view, typically from a nib.
}
//and this method never be called 
- (void)handleNotification:(NSNotification *)notification{
    //处理通知
    //handle notification here

    NSLog(@"current thread:%@",[NSThread currentThread]);

    NSLog(@"handle notification");

}

首先你要知道队列和线程是完全不同的概念。一个队列可能 运行 跨多个线程。

其次,如果您 post 在线程上发出通知,则会在该线程上调用观察者。

所以根据你的代码,肯定不会调用 handleNotification。