NSNotification 發(fā)通知的操作是同步的,并且通知處理是在發(fā)通知的那個線程
如下面的操作:
+ (void)postNotificationAsy {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[[NSThread currentThread] setName:@"test_notifi_thread"];
NSLog(@"begin post notification....");
[[NSNotificationCenter defaultCenter] postNotificationName:testNotification object:nil];
NSLog(@"post notificaition finished...");
});
}
// 這個通知回調(diào)方法是在線程 test_notifi_thread 處理的
- (void)handleNotification:(NSNotification *)notification {
NSLog(@"handle thread name: %@",[NSThread currentThread].name);
NSLog(@"handle Notification...");
}
打印結(jié)果:
ThreadTest[5103:76211] begin post notification....
ThreadTest[5238:83489] handle thread name: test_notifi_thread
ThreadTest[5103:76211] handle Notification...
ThreadTest[5103:76211] post notificaition finished...
1.在test_nofifi_thread線程中發(fā)一條通知 (異步通知)
2.postNotificationName這個方法沒有立即返回,說明是同步的,它會執(zhí)行完對應(yīng)的回調(diào)的方法
3.通知回調(diào)處理是在發(fā)通知的線程(test_nofifi_thread)里處理的
4.postNotificationName這個方法實現(xiàn),應(yīng)該是在調(diào)用線程里去遍歷所有的的NotificationName為Key的Observer列表,然后Observer調(diào)用對應(yīng)注冊的通知處理方法。