標籤:
通常我們在 iOS 中發生什麼事件時該做什麼是由 Delegate 實現的, Apple 還為我們提供了另一種通知回應程式式,那就是 NSNotification.
NSNotificationCenter 較之於 Delegate 可以實現更大的跨度的通訊機制,可以為兩個無參考關聯性的兩個對象進行通訊。NSNotificationCenter 的通訊原理使用了觀察者模式(KVO):三步驟 1在需要實施的地方註冊 2並 寫好觸發的事件 3在需要觸發該事件的地方激發
1. NSNotificationCenter 註冊觀察者對某個事件(以字串命名)感興趣,及該事件觸發時該執行的 Selector 或 Block2. NSNotificationCenter 在某個時機激發事件(以字串命名)3. 觀察者在收到感興趣的事件時,執行相應的 Selector 或 Block
4. 登出觀察者 這個對應註冊 一般在selector方法裡 ,也相對於註冊的時機 一般是 viewWillappear 註冊 viewWillDisapper 登出
//// SecondViewController.m// StoryBoard//// Created by HF on 15/1/12.// Copyright (c) 2015年 YLYL. All rights reserved.//#import "SecondViewController.h"#import "BasicFunctuin.h"@interface SecondViewController ()@end@implementation SecondViewController- (void)viewDidLoad { [super viewDidLoad]; //註冊通知 通知實施方法是update 啟用關鍵字是 @"update" [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update) name:@"update" object:nil];}
//觸發方法-(void) update{ DLog(@"KVO");
//觀察者登出,移除訊息觀察者
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"update" object:nil];
}@end
//// FirstViewController.m// StoryBoard//// Created by wzyb on 14-12-11.// Copyright (c) 2014年 YLYL. All rights reserved.//#import "FirstViewController.h"@interface FirstViewController ()@end@implementation FirstViewController- (void)viewDidLoad { [super viewDidLoad];} -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:YES];
//實施通知 在此時觸發關鍵字@"update" 的通知方法 只要是該關鍵字 方法都執行 [[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:nil];} @end
雖然在 IOS 用上 ARC 後,不顯示移除 NSNotification Observer 也不會出錯,但是這是一個很不好的習慣,不利於效能和記憶體。
移除通知:removeObserver:和removeObserver:name:object:其中,removeObserver:是刪除通知中樞儲存的調度表一個觀察者的所有入口,而removeObserver:name:object: 是刪除匹配了通知中樞儲存的調度表中觀察者的一個入口。
這個比較簡單,直接調用該方法就行。例如:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
注意參數notificationObserver為要刪除的觀察者,一定不能置為nil。
登出觀察者有2個方法:a. 最優的方法,在 UIViewController.m 中:-(void)dealloc {[[NSNotificationCenter defaultCenter] removeObserver:self];}
現在arc中一般post b. 單個移除:[[NSNotificationCenter defaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess" object:nil];
iOS 關於NSNotificationCenter