- 相信小伙伴們平時(shí)沒(méi)怎么注意過(guò)通知是同步還是異步,直到在面試的時(shí)候被面試官問(wèn)的一臉懵逼畅厢,才開(kāi)始思考冯痢,yes or not ?
- 下面我們一起來(lái)揭開(kāi)這個(gè)神秘的面紗:通知到底是同步還是異步框杜?
1.在ViewController.m中創(chuàng)建發(fā)送通知的btn,并注冊(cè)通知
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.backgroundColor = [UIColor greenColor];
[btn setTitle:@"發(fā)送通知" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
btn.frame = CGRectMake(100, 100, 80, 30);
[self.view addSubview:btn];
// 注冊(cè)通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"kNotification" object:nil];
}
2.在btn的按鈕點(diǎn)擊調(diào)用方法中發(fā)送通知:
-(void)btnAction{
//發(fā)送通知浦楣,通知內(nèi)容為:通知發(fā)送了
[[NSNotificationCenter defaultCenter] postNotificationName:@"kNotification" object:@"通知發(fā)送了"];
[NSThread currentThread];
NSLog(@"按鈕點(diǎn)擊了");
}
3.實(shí)現(xiàn)通知發(fā)出后調(diào)用的方法
- (void)notificationAction:(NSNotification *)notifacation{
NSLog(@"%@,%@",notifacation.object,[NSThread currentThread]);
sleep(5);
NSLog(@"通知發(fā)送了完畢");
}
4.接著運(yùn)行程序,點(diǎn)擊發(fā)送通知按鈕
5.我們來(lái)看下log輸出日志
看輸出的順序和時(shí)間就會(huì)發(fā)現(xiàn):在拋出通知以后咪辱,觀察者在通知事件處理完成以后(這里我們休眠5秒)振劳,拋出者才會(huì)往下繼續(xù)執(zhí)行,也就是說(shuō)這個(gè)過(guò)程默認(rèn)是同步的油狂;當(dāng)發(fā)送通知時(shí)历恐,通知中心會(huì)一直等待所有的observer都收到并且處理了通知才會(huì)返回到poster;