当前位置: 首页 > news >正文

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

相关文章:

  • flutter 之proto
  • 深入ArkUI:深入实战组件text和text input
  • 非阻塞 IO(NIO)
  • 第一章 Linux 初探
  • CSS-SVG-环形进度条
  • c语言-string.h库函数初识
  • 使用ArcMap进行选址服务,适宜性分析
  • kubernetes集群 应用实践 kafka部署
  • Vue2+element-ui 实现select选择器结合Tree树形控件实现下拉树效果
  • 将ncnn及opencv的mat存储成bin文件的方法
  • 听GPT 讲Rust源代码--src/tools(27)
  • 什么是高并发系统?
  • ChatGPT4.0(中文版)国内无限制免费版(附网址)
  • 15. 三数之和
  • conda移除环境
  • 【译文】IEEE白皮书 6G 太赫兹技术的基本原理 2023版
  • 【第十二课】KMP算法(acwing-831 / c++代码 / 思路 / 视频+博客讲解推荐)
  • SpringMVC系列之技术点定向爆破一
  • 相比于其他流处理技术,Flink的优点在哪?
  • 3D动态路障生成
  • 海南乐城管理局原局长贾宁已赴省政协工作,曾从河南跨省任职
  • 国家统计局:要持续加大好房子建设供应力度,积极推动城市更新行动和保障房建设
  • 国家统计局:1-4月份,全国固定资产投资同比增长4.0%
  • 倒票“黄牛”屡禁不绝怎么破?业内:强化文旅市场票务公开制度
  • 首次带人形机器人走科技节红毯,傅利叶顾捷:没太多包袱,很多事都能从零开始
  • 精品消费“精”在哪?多在体验上下功夫