09-通知(NSNotification)

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、在需要发送通知的地方,发送通知
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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 通知中心是一个单例。通知在iOS中是一种设计模式。每一个应用程序都有一个通知中心NSNotificationCen...
    丶逐渐阅读 1,168评论 0 1
  • 通知(NSNotification)同协议(Protocol)一样,也是一种在不同对象之间进行通信的机制,与协议相...
    赵亦晨阅读 849评论 0 1
  • 概述 在多数移动应用中任何时候都只能有一个应用程序处于活跃状态,如果其他应用此刻发生了一些用户感兴趣的那么通过通知...
    莫离_焱阅读 6,620评论 1 8
  • 前序 通知在我看来,有好处也有坏处。用好了那就是翻云复海,上天入地,无所不能。什么传值、传递动作就是一句话:天气飘...
    沉默学飞翔阅读 10,505评论 30 38
  • 代理的使用步骤 定义一份代理协议协议名字的格式一般是:类名 + Delegate比如UITableViewDele...
    Yuann阅读 300评论 0 1