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操作。

如有錯誤,歡迎拍磚


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM