與JavaScript
中的事件機制不同,iOS
里的事件廣播機制是同步的,默認(rèn)情況下曹步,廣播一個通知,會阻塞后面的代碼:
-(void) click
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:@"event_happend" object:self];
NSLog(@"HQ1111");
}
按下按鈕后休讳,發(fā)送一個廣播讲婚,此前已經(jīng)注冊了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(@"HQ2222");
}
-(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(@"HQ3333");
}
執(zhí)行這段代碼,首先會輸出HQ2222俊柔,然后是HQ3333筹麸,最后才是HQ1111。調(diào)試發(fā)現(xiàn)雏婶,代碼始終是跑在同一個線程中(廣播事件的線程)物赶,廣播事件之后的代碼被阻塞,直到所有的偵聽者都執(zhí)行完響應(yīng)
所以留晚,由于NotificationCenter
的這個特性块差,如果希望廣播的事件異步處理,則需要在偵聽者的方法里開啟新線程倔丈。應(yīng)該把Notification
作為組件間解耦的方式憨闰,而不是利用它來實現(xiàn)異步處理。