您的位置:首页 > 移动开发 > IOS开发

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作为组件间解耦的方式,而不是利用它来实现异步处理
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: