一、了解幾個相關的類
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,實現傳值。
二、通知的使用流程
首先,我們在需要接收通知的地方注冊觀察者,比如:
1
2
3
4
|
//獲取通知中心單例對象
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
//添加當前類對象為一個觀察者,name和object設置為nil,表示接收一切通知
[center addObserver:self selector:@selector(notice:) name:@
"123"
object:nil];
|
之后,在我們需要時發送通知消息
1
2
3
4
|
//創建一個消息對象
NSNotification * notice = [NSNotification notificationWithName:@
"123"
object:nil userInfo:@{@
"1"
:@
"123"
}];
//發送消息
[[NSNotificationCenter defaultCenter]postNotification:notice];
|
我們可以在回調的函數中取到userInfo內容,如下:
1
2
3
|
-(
void
)notice:(id)sender{
NSLog(@
"%@"
,sender);
}
|
打印結果如下: