NSNotificationCenter通知

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

参考文章

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

NSNotificationCenter

objectivec 复制代码
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;

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

使用方法

添加通知

objectivec 复制代码
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respondsToNotification:) name:@"test" object:nil];
 

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

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

发送通知

objectivec 复制代码
[[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,该参数可以把你需要携带的数据发送给该通知的响应者。

移除通知

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

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

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

NSNotificationCenter声明类

objectivec 复制代码
@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
相关推荐
二流小码农10 小时前
鸿蒙开发:实现一个标题栏吸顶
android·ios·harmonyos
season_zhu11 小时前
iOS开发:关于日志框架
ios·架构·swift
Digitally14 小时前
如何在电脑上轻松访问 iPhone 文件
ios·电脑·iphone
安和昂14 小时前
【iOS】YYModel源码解析
ios
pop_xiaoli15 小时前
UI学习—cell的复用和自定义cell
学习·ui·ios
Daniel_Coder17 小时前
Xcode 16.4 + iOS 18 系统运行时崩溃:___cxa_current_primary_exception 符号丢失的原因与解决方案
ios·xcode·ios 18·dyld·libc++abi
烈焰晴天19 小时前
使用ReactNative加载Svga动画支持三端【Android/IOS/Harmony】
android·react native·ios
sg_knight20 小时前
Flutter嵌入式开发实战 ——从树莓派到智能家居控制面板,打造工业级交互终端
android·前端·flutter·ios·智能家居·跨平台
胖虎11 天前
iOS上传应用包错误问题 “Invalid bundle. The “UIInterfaceOrientationPortrait”“
ios·审核·苹果审核·苹果传包
安和昂1 天前
【iOS】ARC 与 Autorelease
macos·ios·cocoa