1. 程式人生 > >iOS中通知中心NSNotificationCenter應用總結

iOS中通知中心NSNotificationCenter應用總結

iOS中通知中心NSNotificationCenter應用總結
一、瞭解幾個相關的類
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,實現傳值。
3、反向通知,先要有觀察者,通知一發送觀察者就接收到資料。

二、通知的使用流程
首先,我們在需要接收通知的地方註冊觀察者,比如:
//獲取通知中心單例物件

 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);
}

列印結果如下:

注意:問題出現
在解析Nsnotifaction*的過程中 出現了

[NSConcreteNotification objectForKey:]: unrecognized selector sent to instan錯誤

具體原因,是因為在解析noti的資料時候,沒有使用正確的姿勢

NSDictionary *dict = [[NSDictionary alloc] init];
    dict = (NSDictionary*)noti;
    NSLog(@"%@",dict);

以為這樣就可以獲得noti後的字典 其實不然
正確姿勢如下

    NSDictionary *sDict = [[NSDictionary alloc] init];
    sDict = noti.userInfo;
    NSString *s = [sDict objectForKey:@"1"];