ios的notification機制是同步的還是非同步的
阿新 • • 發佈:2019-01-31
與javascript中的事件機制不同,ios裡的事件廣播機制是同步的,預設情況下,廣播一個通知,會阻塞後面的程式碼:
Objc程式碼- -(void) clicked
- {
- NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
- [center postNotificationName:@"event_happend" object:self];
- NSLog(@"all handler done");
- }
按下按鈕後,傳送一個廣播,此前已經註冊了2個此事件的偵聽者
- -(id) init
- {
- self = [super init];
- if(self){
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenReceive:) name:@"event_happend" object:nil];
- }
- return self;
- }
- -(void) whenReceive:(NSNotification*) notification
- {
-
NSLog(@"im1111"
- }
- -(id) init
- {
- self = [super init];
- if(self){
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenReceive:) name:@"event_happend" object:nil];
- }
- return self;
- }
-
-(void) whenReceive:(NSNotification*) notification
- {
- NSLog(@"im22222");
- }
執行這段程式碼,首先會輸出im1111,然後是im22222,最後才是all handler done。除錯發現,程式碼始終是跑在同一個執行緒中(廣播事件的執行緒),廣播事件之後的程式碼被阻塞,直到所有的偵聽者都執行完響應
所以,由於NotificationCenter的這個特性,如果希望廣播的事件非同步處理,則需要在偵聽者的方法裡開啟新執行緒。應該把Notification作為元件間解耦的方式,而不是利用它來實現非同步處理