// 在觀察者對象中注冊通知
[[NSNotificationCenter defaultCenter] addObserverForName:@"NotificationName" object:nil queue:nil usingBlock:^(NSNotification *notification) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 異步處理通知的回調(diào)操作
// 在這里執(zhí)行需要在后臺線程中處理的任務(wù)
// ...
NSLog(@"Notification received on background thread");
});
}];
// 發(fā)送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:nil];
在上面的代碼中,使用 addObserverForName:object:queue:usingBlock: 方法注冊了一個通知觀察者星澳,并在 usingBlock 中處理通知的回調(diào)。在 usingBlock 中,我們使用 dispatch_async 將通知的處理操作放入一個后臺線程中執(zhí)行,從而實現(xiàn)了異步監(jiān)聽通知绒净。
請注意奏瞬,使用 GCD 或其他異步執(zhí)行的機制處理通知時,需要確保在處理通知的回調(diào)過程中不會訪問 UI 相關(guān)的操作指黎,因為 UI 操作必須在主線程中執(zhí)行。如果需要更新 UI 或執(zhí)行其他需要在主線程執(zhí)行的操作州丹,可以使用 dispatch_async(dispatch_get_main_queue(), ^{ /* UI 更新操作 */ }) 將其放入主線程隊列中執(zhí)行醋安。