ios的notification機制是同步的還是非同步

來源:互聯網
上載者:User

標籤:

與javascript中的事件機制不同,ios裡的事件廣播機制是同步的,預設情況下,廣播一個通知,會阻塞後面的代碼:

Objc代碼  
  1. -(void) clicked  
  2. {  
  3.     NSNotificationCenter *center =  [NSNotificationCenter defaultCenter];  
  4.     [center postNotificationName:@"event_happend" object:self];  
  5.       
  6.     NSLog(@"all handler done");  
  7. }  


按下按鈕後,發送一個廣播,此前已經註冊了2個此事件的偵聽者

Objc代碼  
  1. -(id) init  
  2. {  
  3.     self = [super init];  
  4.     if(self){  
  5.         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenReceive:) name:@"event_happend" object:nil];  
  6.     }  
  7.     return self;  
  8. }  
  9.   
  10.   
  11. -(void) whenReceive:(NSNotification*) notification  
  12. {  
  13.     NSLog(@"im1111");  
  14. }  

Objc代碼  
  1. -(id) init  
  2. {  
  3.     self = [super init];  
  4.     if(self){  
  5.         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenReceive:) name:@"event_happend" object:nil];  
  6.     }  
  7.     return self;  
  8. }  
  9.   
  10.   
  11. -(void) whenReceive:(NSNotification*) notification  
  12. {  
  13.     NSLog(@"im22222");  
  14. }  

執行這段代碼,首先會輸出im1111,然後是im22222,最後才是all handler done。調試發現,代碼始終是跑在同一個線程中(廣播事件的線程),廣播事件之後的代碼被阻塞,直到所有的偵聽者都執行完響應

所以,由於NotificationCenter的這個特性,如果希望廣播的事件非同步處理,則需要在偵聽者的方法裡開啟新線程。應該把Notification作為組件間解耦的方式,而不是利用它來實現非同步處理

ios的notification機制是同步的還是非同步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.