1、主线程监听,子线程发通知
- (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]);
}
在主线程监听,子线程发通知,会在子线程接收到通知。
2、子线程监听,子线程发通知
- (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]);
}
子线程监听,子线程发通知,会在发通知的线程里接收到消息
3、子线程监听,主线程发通知
- (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]);
}
子线程监听,主线程发通知,会在主线程接收到消息.
总结:接收通知和发送通知时所在线程一致,和监听时所在线程无关。