標籤:
iOS開發中,每個app都有一個通知中樞,通知中樞可以發送和接收通知。
在使用通知中樞 NSNotificationCenter之前,先瞭解一下通知 NSNotification。
NSNotification 可以理解為訊息對象,包含三個成員變數,如下:
@property (readonly, copy) NSString *name;@property (nullable, readonly, retain) id object;@property (nullable, readonly, copy) NSDictionary *userInfo;
name:通知的名稱
object:針對某一個對象的通知
userInfo:字典類型,主要是用來傳遞參數
建立並初始化一個NSNotification可以使用下面的方法:
+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject;+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
NSNotificationCenter 通知中樞,是一個單例。只能使用 [NSNotificationCenter defaultCenter] 擷取通知中樞對象。
發送通知可以使用下面的方法:
[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil];
或者:
NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"};
NSNotification *notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo]; [[NSNotificationCenter defaultCenter] postNotification:notice];
添加一個觀察者的方法(可以理解成在某個觀察者中註冊通知):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(haveNoti:) name:@"testNotification" object:nil];
有四個參數:第一個參數是觀察者,也就是誰註冊這個通知;第二個參數是當接收到通知時的回呼函數;第三個參數是通知的名稱,通知名是區分各個通知的唯一標識;第四個參數是接收哪個對象發過來的通知,如果為nil,則接收任何對象發過來的該通知。
移除觀察者,兩種方法:
- (void)removeObserver:(id)observer;- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
NSNotificationCenter 的使用舉例如下:
發送通知(兩種方法):
- (void)btnClicked{ //[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil]; NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"}; NSNotification *notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo]; [[NSNotificationCenter defaultCenter] postNotification:notice]; }
增加觀察者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(haveNoti:) name:@"testNotification" object:nil];
回呼函數(可以利用回呼函數的參數 notification獲得該通知的資訊,比如name、object、參數):
- (void)haveNoti:(NSNotification *)notification{ NSLog(@"name = %@",[notification name]); NSDictionary *userInfo = [notification userInfo]; NSLog(@"info = %@",userInfo);}
針對某一個特定對象的通知的使用情境:
UITextField,比如說我們要監聽UITextField 裡面內容的變化,此時可以註冊下面的通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarTextChange) name:UITextFieldTextDidChangeNotification object:self.searchBar];
self.searchBar 是 UITextField 類型。
iOS 通知中樞 NSNotificationCenter