NSNotification通知是同步还是异步?
2016-11-24 本文已影响289人
abigfishBegonia
- 相信小伙伴们平时没怎么注意过通知是同步还是异步,直到在面试的时候被面试官问的一脸懵逼,才开始思考,yes or not ?
- 下面我们一起来揭开这个神秘的面纱:通知到底是同步还是异步?
1.在ViewController.m中创建发送通知的btn,并注册通知
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.backgroundColor = [UIColor greenColor];
[btn setTitle:@"发送通知" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
btn.frame = CGRectMake(100, 100, 80, 30);
[self.view addSubview:btn];
// 注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"kNotification" object:nil];
}
2.在btn的按钮点击调用方法中发送通知:
-(void)btnAction{
//发送通知,通知内容为:通知发送了
[[NSNotificationCenter defaultCenter] postNotificationName:@"kNotification" object:@"通知发送了"];
[NSThread currentThread];
NSLog(@"按钮点击了");
}
3.实现通知发出后调用的方法
- (void)notificationAction:(NSNotification *)notifacation{
NSLog(@"%@,%@",notifacation.object,[NSThread currentThread]);
sleep(5);
NSLog(@"通知发送了完毕");
}
4.接着运行程序,点击发送通知按钮

5.我们来看下log输出日志

看输出的顺序和时间就会发现:在抛出通知以后,观察者在通知事件处理完成以后(这里我们休眠5秒),抛出者才会往下继续执行,也就是说这个过程默认是同步的;当发送通知时,通知中心会一直等待所有的observer都收到并且处理了通知才会返回到poster;