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
相关推荐
Magnetic_h11 小时前
【iOS】单例模式
笔记·学习·ui·ios·单例模式·objective-c
归辞...13 小时前
「iOS」——单例模式
ios·单例模式·cocoa
yanling202315 小时前
黑神话悟空mac可以玩吗
macos·ios·crossove·crossove24
归辞...17 小时前
「iOS」viewController的生命周期
ios·cocoa·xcode
crasowas21 小时前
Flutter问题记录 - 适配Xcode 16和iOS 18
flutter·ios·xcode
2401_8524035521 小时前
Mac导入iPhone的照片怎么删除?快速方法讲解
macos·ios·iphone
SchneeDuan21 小时前
iOS六大设计原则&&设计模式
ios·设计模式·cocoa·设计原则
JohnsonXin2 天前
【兼容性记录】video标签在 IOS 和 安卓中的问题
android·前端·css·ios·h5·兼容性
蒙娜丽宁2 天前
Go语言错误处理详解
ios·golang·go·xcode·go1.19
名字不要太长 像我这样就好2 天前
【iOS】push和pop、present和dismiss
学习·macos·ios·objective-c·cocoa