NSNotificationCenter通知

使用观察者模式来实现的用于跨层传递消息的机制

参考文章

ios消息机制(NSNotification 和 NSNotificationCenter)
透彻理解 NSNotificationCenter 通知(含实现代码) - 掘金

NSNotificationCenter

@property (class, readonly, strong) NSNotificationCenter *defaultCenter;

该属性是获取 NSNotificationCenter 唯一单例,它就是一个消息分发中心,通过使用这个唯一的实例我们进行添加通知、发送通知和移除通知

使用方法

添加通知

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respondsToNotification:) name:@"test" object:nil];
 

Observer为响应者,selector为一个响应通知的方法,name是一个标识,通知中心主要是通过它来实现消息的精确分发。

registerForNotifications:注册通知在viewdidload里面调用

发送通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil userInfo:nil];

//使用NSNotification
NSNotification *notification = [[NSNotification alloc] initWithName:@"test0" object:_obj2 userInfo:@{
   @"key":@"_obj2"}];
[[NSNotificationCenter defaultCenter] postNotification:notification];

发送通知和添加通知对应,需要name、object参数,这里多了一个userInfo,该参数可以把你需要携带的数据发送给该通知的响应者。

移除通知

//移除该响应者的全部通知
[[NSNotificationCenter defaultCenter]  removeObserver:self];

//移除该响应者 name == @"test" 的全部通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"test" object:nil];

unregisterFromNotifications:移除通知在dealloc里面调用

NSNotificationCenter声明类

@interface NSNotificationCenter : NSObject
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;
@end

相关推荐

  1. NSNotificationCenter通知

    2023-12-28 00:46:02       42 阅读
  2. Android 判断通知是进度条通知

    2023-12-28 00:46:02       25 阅读
  3. 非常抱歉的通知

    2023-12-28 00:46:02       41 阅读
  4. SpringBootAdmin设置邮件通知

    2023-12-28 00:46:02       34 阅读
  5. FreeRTOS任务通知

    2023-12-28 00:46:02       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-28 00:46:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-28 00:46:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-28 00:46:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-28 00:46:02       20 阅读

热门阅读

  1. 网站开发:初学者深入指南

    2023-12-28 00:46:02       23 阅读
  2. Django 安装

    2023-12-28 00:46:02       37 阅读
  3. CommandLineRunner接口和@PostConstruct

    2023-12-28 00:46:02       29 阅读
  4. 基于OpenCV的图像颜色与形状识别的原理2

    2023-12-28 00:46:02       40 阅读
  5. 丢失的数字

    2023-12-28 00:46:02       35 阅读
  6. 创建ROS的软件包服务器

    2023-12-28 00:46:02       39 阅读
  7. 【AUTOSAR】软件架构中的接口设计与跨核通信解析

    2023-12-28 00:46:02       42 阅读
  8. kubernetes面试之calico网络组件的实现原理

    2023-12-28 00:46:02       46 阅读
  9. C语言第五十七弹---模拟使用memmove函数

    2023-12-28 00:46:02       38 阅读
  10. 【uniapp】Uniapp cli 自动化打包脚本实现

    2023-12-28 00:46:02       44 阅读
  11. uniapp常见的标签

    2023-12-28 00:46:02       44 阅读
  12. 1.Linux是什么与如何学习

    2023-12-28 00:46:02       42 阅读