IOS中通知中心(NSNotificationCenter)的使用總結

NSNotification 是iOS中一個調度消息通知的類,采用單例模式設計,在程序中實現傳值、回調等地方應用很廣。

一、了解幾個相關的類


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

這個類是一個通知中心,使用單例設計,每個應用程序都會有一個默認的通知中心。用于調度通知的發送的接受。

添加一個觀察者,可以為它指定一個方法,名字和對象。接受到通知時,執行方法。

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

發送通知消息的方法

- (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、如果發送的通知指定了object對象,那么觀察者接收的通知設置的object對象與其一樣,才會接收到通知,但是接收通知如果將這個參數設置為了nil,則會接收一切通知。

2、觀察者的SEL函數指針可以有一個參數,參數就是發送的死奧西對象本身,可以通過這個參數取到消息對象的userInfo,實現傳值。


二、通知的使用流程


1.通知的創建與發送

在需要發送通知的界面中創建通知

/** 返回到上個界面 */

- (IBAction)back:(id)sender {

// 1.添加字典, 將數據包到字典中

NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"小明",@"name",@"111401",@"number", nil];

// 2.創建通知

NSNotification *notification =[NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];

// 3.通過 通知中心 發送 通知

[[NSNotificationCenter defaultCenter] postNotification:notification];

[self dismissViewControllerAnimated:YES completion:nil];

}

2.通知的接收

在需要接收的控制器中注冊通知監聽者,將通知發送的信息接收

- (void)viewDidLoad {

[super viewDidLoad];

// 1.注冊通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction:) name:@"InfoNotification" object:nil];

}

// 2.實現收到通知觸發的方法

- (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];

注意參數notificationObserver為要刪除的觀察者,一定不能置為nil。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容