ios的notification机制是同步的
2014-02-20 19:45
316 查看
与javascript中的事件机制不同,ios里的事件广播机制是同步的,默认情况下,广播一个通知,会阻塞后面的代码:
按下按钮后,发送一个广播,此前已经注册了2个此事件的侦听者
执行这段代码,首先会输出im1111,然后是im22222,最后才是all handler done。调试发现,代码始终是跑在同一个线程中(广播事件的线程),广播事件之后的代码被阻塞,直到所有的侦听者都执行完响应
所以,由于NotificationCenter的这个特性,如果希望广播的事件异步处理,则需要在侦听者的方法里开启新线程。应该把Notification作为组件间解耦的方式,而不是利用它来实现异步处理
-(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"); }
执行这段代码,首先会输出im1111,然后是im22222,最后才是all handler done。调试发现,代码始终是跑在同一个线程中(广播事件的线程),广播事件之后的代码被阻塞,直到所有的侦听者都执行完响应
所以,由于NotificationCenter的这个特性,如果希望广播的事件异步处理,则需要在侦听者的方法里开启新线程。应该把Notification作为组件间解耦的方式,而不是利用它来实现异步处理
相关文章推荐
- ios的notification机制是同步的还是异步的
- ios的notification机制是同步的还是异步的
- [iOS基础控件 - 6.10] Notification 通知机制
- IOS学习之NSNotificationCenter消息机制
- iOS学习笔记6-关于NSNotificationCenter及同步异步
- ios开发中的基本设计模式(代理,观察者,MVC,单例,策略,工厂,MVVM,原型,Target-Action,通知(notification)机制)
- IOS开发数据传递机制之NSNotificationCenter
- iOS中有两种支持机制:Notification和KVO(Key-Value Observing)
- iOS 线程锁同步机制
- iOS设计模式 - 通知机制(Notification)
- iOS学习笔记之NSNotificationCenter(消息机制)
- iOS高级面试之NSNotificationCenter是同步操作还是异步操作
- ios同步机制
- iOS中消息传递机制(KVO,Notification,delegation,block,Target-Action)
- 缓存同步机制整理
- 多线程之旅之四——浅谈内存模型和用户态同步机制
- iOS反射机制
- iOS 7 Background Remote Notification
- 电商之 Mobile 里多变活动页 与 IOS APP,Android APP 里的 活动页 如何保持同步,解决方案
- JAVA之旅(十四)——静态同步函数的锁是class对象,多线程的单例设计模式,死锁,线程中的通讯以及通讯所带来的安全隐患,等待唤醒机制