首先,我們在需要接收通知的地方注冊觀察者,比如:
//獲取通知中心單例對象
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
//添加當前類對象為一個觀察者,name和object設置為nil,表示接收一切通知
[center addObserver:self selector:@selector(notice:) name:@"123" object:nil];
之后,在我們需要時發送通知消息
//創建一個消息對象
NSNotification * notice = [NSNotification notificationWithName:@"123" object:nil userInfo:@{@"1":@"123"}];
//發送消息
[[NSNotificationCenter defaultCenter]postNotification:notice];
我們可以在回調的函數中取到userInfo內容,如下:
-(void)notice:(id)sender{
NSLog(@"%@",sender);
}
打印結果如下:
104111_TqQ7_2340880.png