iOS NSNotificationCenter

NSNotification 是iOS中一个调度消息通知的类,采用单例模式设计,在程序中实现传值、回调等地方应用很广。

一、通知的使用三步走

1.通知的创建与发送

在需要发送通知的界面中创建通知

// 1.添加字典, 将数据包到字典中
NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"小明",@"name",@"111401",@"number", nil];

// 2.创建通知
NSNotification *notification =[NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];

// 3.通过 通知中心 发送 通知
[[NSNotificationCenter defaultCenter] postNotification:notification];
[self dismissViewControllerAnimated:YES completion:nil];

2.通知的接收

在需要接收的控制器中注册通知监听者,将通知发送的信息接收

// 1.注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction:) name:@"InfoNotification" object:nil];
// 2.实现收到通知触发的方法

- (void)InfoNotificationAction:(NSNotification *)notification{

      NSLog(@"%@",notification.userInfo);
      NSLog(@"---接收到通知---");
}

3.通知的移除

移除通知:

[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];

注意参数notificationObserver为要删除的观察者,一定不能置为nil。

二、相关类

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;
几点注意:
  • 如果发送的通知指定了object对象,那么观察者接收的通知设置的object对象与其一样,才会接收到通知,但是接收通知如果将这个参数设置为了nil,则会接收一切通知。

  • 观察者的SEL函数指针可以有一个参数,参数就是发送的死奥西对象本身,可以通过这个参数取到消息对象的userInfo,实现传值。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • OC语言基础 1.类与对象 类方法 OC的类方法只有2种:静态方法和实例方法两种 在OC中,只要方法声明在@int...
    奇异果好补阅读 4,360评论 0 11
  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 13,983评论 0 15
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,667评论 8 265
  • 生活就像海洋,只有益智坚强的人,才能到达彼岸! 当我们努力使自己变得比现在更好地时候,我们周围的一切也会变得更好。
    瑞TYSS阅读 100评论 0 0
  • 正所谓 赠人玫瑰,手有余香 赠人以书,受用终生 于是乎 小捕为了技术宅们的终生决定开展赠书活动 主题 作为Andr...
    f9dd77add98e阅读 606评论 0 0