- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:)
name:kNotificationName object:nil];
}
- (void) notificationAction: (NSNotification*)notification
{
NSLog(@"sleep 之前");
sleep(10);
NSLog(@"sleep 之后");
}
- (void)buttonActon:(id)sender{
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:nil];
NSLog(@"buttonActon:");
}
// 打印順序如下:
sleep 之前
sleep 之后
buttonActon:
結論:
(1)NSNotificationCenter 默認是同步的,在通知發出之后,觀察者要處理完通知事件之后,通知的發送者才能繼續往下執行。
(2)NSNotificationCenter 會一直等待所有的 觀察者 都收到并且處理了通知才會返回到 通知發送者。
(3)如果想NSNotificationCenter不阻塞當前線程,可以根據實際情況,考慮將通知的發送放在子線程,或者將通知的處理方法放在子線程調用。