NSNotification 是iOS中一個調度消息通知的類,采用單例模式設計,在程序中實現(xiàn)傳值、回調等地方應用很廣。
一、了解幾個相關的類
1、NSNotification
這個類可以理解為一個消息對象,其中有三個成員變量。
這個成員變量是這個消息對象的唯一標識,用于辨別消息對象。
@property (readonly, copy) NSString *name;
這個成員變量定義一個對象,可以理解為針對某一個對象的消息。
@property (readonly, retain) id object;
這個成員變量是一個字典,可以用其來進行傳值。
@property (readonly, copy) NSDictionary *userInfo;
NSNotification的初始化方法:
- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo;
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
注意:官方文檔有明確的說明,不可以使用init進行初始化
2、NSNotificationCenter
這個類是一個通知中心,使用單例設計,每個應用程序都會有一個默認的通知中心。用于調度通知的發(fā)送的接受。
添加一個觀察者,可以為它指定一個方法,名字和對象。接受到通知時,執(zhí)行方法。
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
發(fā)送通知消息的方法
- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSString *)aName object:(id)anObject;
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
移除觀察者的方法
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
幾點注意:
1、如果發(fā)送的通知指定了object對象,那么觀察者接收的通知設置的object對象與其一樣,才會接收到通知,但是接收通知如果將這個參數(shù)設置為了nil,則會接收一切通知。
2、觀察者的SEL函數(shù)指針可以有一個參數(shù),參數(shù)就是發(fā)送的死奧西對象本身,可以通過這個參數(shù)取到消息對象的userInfo,實現(xiàn)傳值。
二、通知的使用流程
1.通知的創(chuàng)建與發(fā)送
在需要發(fā)送通知的界面中創(chuàng)建通知
/** 返回到上個界面 */
- (IBAction)back:(id)sender {
// 1.添加字典, 將數(shù)據(jù)包到字典中
NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"小明",@"name",@"111401",@"number", nil];
// 2.創(chuàng)建通知
NSNotification *notification =[NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];
// 3.通過 通知中心 發(fā)送 通知
[[NSNotificationCenter defaultCenter] postNotification:notification];
[self dismissViewControllerAnimated:YES completion:nil];
}
2.通知的接收
在需要接收的控制器中注冊通知監(jiān)聽者,將通知發(fā)送的信息接收
- (void)viewDidLoad {
[super viewDidLoad];
// 1.注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction:) name:@"InfoNotification" object:nil];
}
// 2.實現(xiàn)收到通知觸發(fā)的方法
- (void)InfoNotificationAction:(NSNotification *)notification{
NSLog(@"%@",notification.userInfo);
NSLog(@"---接收到通知---");
}
3.通知的移除
移除通知:removeObserver:和removeObserver:name:object:
其中,removeObserver:是刪除通知中心保存的調度表一個觀察者的所有入口,而removeObserver:name:object:是刪除匹配了通知中心保存的調度表中觀察者的一個入口。
這個比較簡單,直接調用該方法就行。例如:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
注意參數(shù)notificationObserver為要刪除的觀察者,一定不能置為nil。