ios的notification机制是同步的还是异步的

来源:互联网 发布:淘宝账号异常 编辑:程序博客网 时间:2024/05/16 01:14

与javascript中的事件机制不同,ios里的事件广播机制是同步的,默认情况下,广播一个通知,会阻塞后面的代码:

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


按下按钮后,发送一个广播,此前已经注册了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.   
  10.   
  11. -(void) whenReceive:(NSNotification*) notification  
  12. {  
  13.     NSLog(@"im1111");  
  14. }  

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.   
  10.   
  11. -(void) whenReceive:(NSNotification*) notification  
  12. {  
  13.     NSLog(@"im22222");  
  14. }  

执行这段代码,首先会输出im1111,然后是im22222,最后才是all handler done。调试发现,代码始终是跑在同一个线程中(广播事件的线程),广播事件之后的代码被阻塞,直到所有的侦听者都执行完响应

所以,由于NotificationCenter的这个特性,如果希望广播的事件异步处理,则需要在侦听者的方法里开启新线程。应该把Notification作为组件间解耦的方式,而不是利用它来实现异步处理

1 0
原创粉丝点击