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
相关推荐
二流小码农9 天前
鸿蒙开发:基于node脚本实现组件化运行
android·ios·harmonyos
依旧风轻9 天前
Domain 层完全指南(面向 iOS 开发者)
ios·domain·entity·sqi
续天续地9 天前
开箱即用的Kotlin Multiplatform 跨平台开发模板:覆盖网络/存储/UI/DI/CI工具链
ios·kotlin
minos.cpp9 天前
从厨房到代码台:用做菜思维理解iOS开发 - Swift入门篇①
ios·蓝桥杯·swift
杂雾无尘10 天前
开发者必看,全面解析 iOS 架构,探索 iOS 背后的秘密!
ios·swift·apple
Digitally10 天前
如何使用 USB 数据线将文件从 PC 传输到 iPhone
ios·iphone
二流小码农10 天前
鸿蒙开发:基于DevEco Studio插件实现组件化运行
android·ios·harmonyos
kymjs张涛10 天前
前沿技术周刊 2025-06-23
android·ios·app
YungFan10 天前
iOS26适配指南之@Observable Object
ios·swift
杂雾无尘10 天前
不为人知的技巧:Swift 中用特有方法实现"黑魔法"方法交换
ios·swift·客户端