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

iOS中通知中心NSNotificationCenter應用總結

1、瞭解幾個相關的類

一、NSNotification

這個類能夠理解爲一個消息對象,其中有三個成員變量。函數

這個成員變量是這個消息對象的惟一標識,用於辨別消息對象。post

 

@property (readonly, copy) NSString *name;學習

 

這個成員變量定義一個對象,能夠理解爲針對某一個對象的消息。spa

 

@property (readonly, retain) id object;.net

 

這個成員變量是一個字典,能夠用其來進行傳值。設計

 

@property (readonly, copy) NSDictionary *userInfo;指針

 

NSNotification的初始化方法:code

 

- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo;server

 

+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;對象

 

+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

 

注意:官方文檔有明確的說明,不可使用init進行初始化

二、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;

 

幾點注意:

一、若是發送的通知指定了object對象,那麼觀察者接收的通知設置的object對象與其同樣,纔會接收到通知,可是接收通知若是將這個參數設置爲了nil,則會接收一切通知。

二、觀察者的SEL函數指針能夠有一個參數,參數就是發送的死奧西對象自己,能夠經過這個參數取到消息對象的userInfo,實現傳值。

 

2、通知的使用流程

首先,咱們在須要接收通知的地方註冊觀察者,好比:

    //獲取通知中心單例對象
    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);
}

打印結果以下:

 

疏漏之處 歡迎指正

學習使用 歡迎轉載

專一技術,熱愛生活,交流技術,也作朋友。

——琿少 QQ羣:203317592

相關文章
相關標籤/搜索