ios跨线程通知_iOS中关于NotificationCenter通知线程问题
- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.self.title=@"测试类";dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{[[NSNotific
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title=@"测试类";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(xxx) name:@"xxx" object:nil];
NSLog(@"子线程注册通知===%@",[NSThread currentThread]);
});
NSLog(@"主线程===%@",[NSThread currentThread]);
UIButton *sendBtn=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
sendBtn.backgroundColor=[UIColor redColor];
[sendBtn setTitle:@"发送通知" forState:UIControlStateNormal];
[sendBtn addTarget:self action:@selector(sendNoti) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sendBtn];
// Do any additional setup after loading the view.
}
-(void)sendNoti
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"xxx" object:nil];
NSLog(@"发送通知子线线程===%@",[NSThread currentThread]);
});
}
-(void)xxx
{
NSLog(@"收到通知线程===%@",[NSThread currentThread]);
}
打印结果:
1、子线程注册 子线程发送
主线程==={number = 1, name = main}
子线程注册通知==={number = 3, name = (null)}
收到通知线程==={number = 4, name = (null)}
发送通知子线线程==={number = 4, name = (null)}
2、主线程注册 子线程发送
主线程注册通知==={number = 1, name = main}
收到通知线程==={number = 3, name = (null)}
发送通知子线线程==={number = 3, name = (null)}
结论:
不管你在哪个线程注册通知,发送通知在哪个线程,接受通知就会在哪个线程,即发送通知和接受通知在同一个线程,因此,若要更新UI的操作时,需要切入主线程
注意:通知触发的方法是同步执行,所以通知会有延迟
更多推荐
所有评论(0)