ios的notification机制是同步的还是异步的
2017-06-19 16:03
323 查看
与javascript中的事件机制不同。ios里的事件广播机制是同步的,默认情况下。广播一个通知,会堵塞后面的代码:
Objc代码
-(void) clicked
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:@"event_happend" object:self];
NSLog(@"all handler done");
}
按下button后。发送一个广播。此前已经注冊了2个此事件的侦听者
Objc代码
-(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");
}
Objc代码
-(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作为组件间解耦的方式,而不是利用它来实现异步处理
Objc代码
-(void) clicked
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:@"event_happend" object:self];
NSLog(@"all handler done");
}
按下button后。发送一个广播。此前已经注冊了2个此事件的侦听者
Objc代码
-(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");
}
Objc代码
-(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高级面试之NSNotificationCenter是同步操作还是异步操作
- ios的notification机制是同步的
- iOS学习笔记6-关于NSNotificationCenter及同步异步
- iOS-NSNotificationCenter通知中心是同步操作还是异步操作
- iOS中GET请求的同步与异步
- 【java回调】同步/异步回调机制的原理和使用方法
- ios的线程和同步异步操作
- iOS开发之网络编程篇三:同步,异步请求差异及用法
- IOS中get同步异步请求与post同步异步请求
- Java 异步机制与同步机制的区别
- ios开发中的基本设计模式(代理,观察者,MVC,单例,策略,工厂,MVVM,原型,Target-Action,通知(notification)机制)
- 异步(Asynchronous)机制(三)--和同步机制的本质区别
- iOS GCD, 同步,异步,串行队列,并行队列,dispatch_group
- java 异步机制与同步机制的区别
- IOS 同步请求和异步请求
- java 三种调用机制(同步、回调、异步)
- IOS之同步请求、异步请求、GET请求、POST请求
- 可以运行测试的IOS同步请求、异步请求、GET请求、POST请求
- IOS 调用WebService(同步和异步)