1. 程式人生 > >ios的notification機制是同步的還是非同步的

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

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

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

按下按鈕後,傳送一個廣播,此前已經註冊了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. -(void) whenReceive:(NSNotification*) notification  
  10. {  
  11.     NSLog(@"im1111"
    );  
  12. }  
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. -(void) whenReceive:(NSNotification*) notification  
  10. {  
  11.     NSLog(@"im22222");  
  12. }  

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

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