1. The main thread listens, and the child thread sends notifications
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"1"); dispatch_queue_t queue = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL); dispatch_async(queue, ^{ NSLog(@"serial %@",[NSThread currentThread]); [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil]; }); NSLog(@"2"); } - (void)receive { NSLog(@"receive %@",[NSThread currentThread]); } @endCopy the code
On the main thread listening, the child thread sending notification, will receive notification on the child thread.
2. The child thread listens, and the child thread sends notifications
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"global%@",[NSThread currentThread]); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil]; }); } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"1"); dispatch_queue_t queue = dispatch_queue_create("serial", DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ NSLog(@"serial %@",[NSThread currentThread]); [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil]; }); NSLog(@"2"); } - (void)receive { NSLog(@"receive %@",[NSThread currentThread]); } @endCopy the code
The child thread listens, the child thread sends the notification, and it receives the message in the thread that sends the notification
3. The child thread listens, and the main thread sends notifications
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"global%@",[NSThread currentThread]); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil]; }); } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"1"); NSLog(@"serial %@",[NSThread currentThread]); [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil]; NSLog(@"2"); } - (void)receive { NSLog(@"receive %@",[NSThread currentThread]); } @endCopy the code
The child thread listens, the main thread notifies, and it receives messages on the main thread.