1绽淘、主線程監(jiān)聽(tīng)涵防,子線程發(fā)通知
- (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]);
}
在主線程監(jiān)聽(tīng),子線程發(fā)通知沪铭,會(huì)在子線程接收到通知壮池。
2偏瓤、子線程監(jiān)聽(tīng),子線程發(fā)通知
- (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]);
}
子線程監(jiān)聽(tīng)椰憋,子線程發(fā)通知厅克,會(huì)在發(fā)通知的線程里接收到消息
3、子線程監(jiān)聽(tīng)熏矿,主線程發(fā)通知
- (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]);
}
子線程監(jiān)聽(tīng)已骇,主線程發(fā)通知,會(huì)在主線程接收到消息.
總結(jié):接收通知和發(fā)送通知時(shí)所在線程一致,和監(jiān)聽(tīng)時(shí)所在線程無(wú)關(guān)票编。