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
這個類是一個通知中心,使用單例設計,每個應用程序都會有一個默認的通知中心。用于調度通知的發(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對象,那么觀察者接收的通知設置的object對象與其一樣,才會接收到通知,但是接收通知如果將這個參數設置為了nil,則會接收一切通知。
2、觀察者的SEL函數指針可以有一個參數,參數就是發(fā)送的死奧西對象本身,可以通過這個參數取到消息對象的userInfo,實現傳值。
通知使用流程
- 1、在需要發(fā)送通知的地方,發(fā)送通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:MSA_LOGIN_NOTIFICATION object:nil userInfo:@{@"errorCode" : @0 , @"ticket" : model.authTicket}];
- 2、接受通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(verifySSOTicket:) name:MSA_LOGIN_NOTIFICATION object:nil];
// 登錄結果(接收通知后要做的事情)
- (void)verifySSOTicket:(NSNotification *)notic
{
NSLog(@"notic:%@", notic.userInfo);
ViewController *vc = [[ViewController alloc] init];
self.window.rootViewController = vc;
}