標籤:
與javascript中的事件機制不同,ios裡的事件廣播機制是同步的,預設情況下,廣播一個通知,會阻塞後面的代碼:
Objc代碼
- -(void) clicked
- {
- NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
- [center postNotificationName:@"event_happend" object:self];
-
- NSLog(@"all handler done");
- }
按下按鈕後,發送一個廣播,此前已經註冊了2個此事件的偵聽者
Objc代碼
- -(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");
- }
Objc代碼
- -(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作為組件間解耦的方式,而不是利用它來實現非同步處理
ios的notification機制是同步的還是非同步