与javascript中的事件机制不同,ios里的事件广播机制是同步的,默认情况下,广播一个通知,会阻塞后面的代码:
-(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"); }
所以,由于NotificationCenter的这个特性,如果希望广播的事件异步处理,则需要在侦听者的方法里开启新线程。应该把Notification作为组件间解耦的方式,而不是利用它来实现异步处理