iOS中通知中心NSNotificationCenter的使用

首先,我們在需要接收通知的地方注冊觀察者,比如:

//獲取通知中心單例對象
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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容