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
相关推荐
初级代码游戏5 小时前
iOS开发 SwiftUI 14:ScrollView 滚动视图
ios·swiftui·swift
初级代码游戏7 小时前
iOS开发 SwitftUI 13:提示、弹窗、上下文菜单
ios·swiftui·swift·弹窗·消息框
zhyongrui10 小时前
托盘删除手势与引导体验修复:滚动冲突、画布消失动画、气泡边框
ios·性能优化·swiftui·swift
Boxsc_midnight13 小时前
【openclaw+imessage】【免费无限流量】集成方案,支持iphone手机+macos
ios·智能手机·iphone
感谢地心引力1 天前
安卓、苹果手机无线投屏到Windows
android·windows·ios·智能手机·安卓·苹果·投屏
仙剑魔尊重楼1 天前
iMazing 3.1.3官方中文版新功能介绍
macos·objective-c·cocoa
2501_915918411 天前
HTTPS 代理失效,启用双向认证(mTLS)的 iOS 应用网络怎么抓包调试
android·网络·ios·小程序·https·uni-app·iphone
Swift社区1 天前
Flutter 路由系统,对比 RN / Web / iOS 有什么本质不同?
前端·flutter·ios
zhyongrui1 天前
SnipTrip 发热优化实战:从 60Hz 到 30Hz 的性能之旅
ios·swiftui·swift
Andy Dennis1 天前
ios开发 xcode配置
ios·cocoa·xcode