IOS中通知中心(NSNotificationCenter)的使用总结
IOS中通知中心NSNotificationCenter應(yīng)用總結(jié)
一、了解幾個相關(guān)的類
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
這個類是一個通知中心,使用單例設(shè)計,每個應(yīng)用程序都會有一個默認的通知中心。用于調(diào)度通知的發(fā)送的接受。
添加一個觀察者,可以為它指定一個方法,名字和對象。接受到通知時,執(zhí)行方法。
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString?*)aName object:(id)anObject;
發(fā)送通知消息的方法
- (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、如果發(fā)送的通知指定了object對象,那么觀察者接收的通知設(shè)置的object對象與其一樣,才會接收到通知,但是接收通知如果將這個參數(shù)設(shè)置為了nil,則會接收一切通知。
2、觀察者的SEL函數(shù)指針可以有一個參數(shù),參數(shù)就是發(fā)送的死奧西對象本身,可以通過這個參數(shù)取到消息對象的userInfo,實現(xiàn)傳值。
二、通知的使用流程
首先,我們在需要接收通知的地方注冊觀察者,比如:
?| 1 2 3 4 | ????//獲取通知中心單例對象 ????NSNotificationCenter?*?center?=?[NSNotificationCenter?defaultCenter]; ????//添加當(dāng)前類對象為一個觀察者,name和object設(shè)置為nil,表示接收一切通知 ????[center?addObserver:self?selector:@selector(notice:)?name:@"123"?object:nil]; |
之后,在我們需要時發(fā)送通知消息
| 1 2 3 4 | ????//創(chuàng)建一個消息對象 ????NSNotification?*?notice?=?[NSNotification?notificationWithName:@"123"?object:nil?userInfo:@{@"1":@"123"}]; ????//發(fā)送消息 ???????[[NSNotificationCenter?defaultCenter]postNotification:notice]; |
我們可以在回調(diào)的函數(shù)中取到userInfo內(nèi)容,如下:
| 1 2 3 | -(void)notice:(id)sender{ ????NSLog(@"%@",sender); } |
打印結(jié)果如下:
總結(jié)
以上是生活随笔為你收集整理的IOS中通知中心(NSNotificationCenter)的使用总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS7.0 安装nginx-1.
- 下一篇: shell-----函数库调用