iOS通知线程处理

准备

测试项目中点击ViewController界面跳转到SecondTestViewController中,再点击SecondTestViewController时返回到ViewController,并且将ViewController中一个view的背景颜色设置为红色。

代码示例:

  • 通知发送点在主线程中的时候接收调用的方法也在主线程执行
//发送位置 SecondTestViewController
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_NAME object:nil userInfo:nil];
    NSLog(@"当前线程 发送 %@", [NSThread currentThread]);
    [self.navigationController popViewControllerAnimated:YES];
    
//接收位置ViewController
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:NOTIFICATION_NAME object:nil];
- (void)handleNotification:(NSNotification *)notification
{
    self.changeView.backgroundColor = [UIColor redColor];
    NSLog(@"当前线程 设置背景  %@", [NSThread currentThread]);
}
//输出
当前线程 设置背景  <NSThread: 0x60c0000750c0>{number = 1, name = main}
当前线程 发送 <NSThread: 0x60c0000750c0>{number = 1, name = main}

  • 通知发送在global时,经测试其在同一线程
//发送点
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"当前线程 发送 %@", [NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_NAME object:nil userInfo:nil];
    });
    
//接收点
	self.changeView.backgroundColor = [UIColor redColor];
    NSLog(@"当前线程 设置背景  %@", [NSThread currentThread]);
    
//输出
当前线程 发送 <NSThread: 0x6080004632c0>{number = 3, name = (null)}
当前线程 设置背景  <NSThread: 0x6080004632c0>{number = 3, name = (null)}
//同时在接收点提示警告“-[UIView setBackgroundColor:] must be used from main thread only”
    
  • 我们创建一个子线程让其中发送通知
//发送
 dispatch_queue_t queue = dispatch_queue_create("sss", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSLog(@"当前线程 发送 %@", [NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_NAME object:nil userInfo:nil];
    });
    
//接收
	self.changeView.backgroundColor = [UIColor redColor];
    NSLog(@"当前线程 设置背景  %@", [NSThread currentThread]);
    
//输出
当前线程 发送 <NSThread: 0x608000078900>{number = 3, name = (null)}
当前线程 设置背景  <NSThread: 0x608000078900>{number = 3, name = (null)}
//同时在接收点提示警告“-[UIView setBackgroundColor:] must be used from main thread only”

官方文档:在多线程的程序中,通知会在post通知时所在的线程被传达,这就导致了观察者注册通知的线程和收到通知的线程不在一个线程。

总结:通过上面的示例可以初步得出结论Notification的发送处理一般在同一线程,所以当我们在子线程发送了通知后在接收端如果涉及到UI操作的部分不要忘记返回到主线程后再进行UI操作。

如有错误,欢迎拍砖

原文地址:https://www.cnblogs.com/GoodmorningMr/p/9661213.html