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

与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. }  


按下button后。发送一个广播。此前已经注冊了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作为组件间解耦的方式,而不是利用它来实现异步处理

转载于:https://www.cnblogs.com/cxchanpin/p/7049120.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值