通知类本身比较简单,大概就分为注册通知监听器、发送通知,注销通知监听器三个方法;通知中心(NSNotificationCenter)采用单例的模式,整个系统只有一个通知中心,通过如下代码获取:
?
|
1
2
|
//获取通知中心
[NSNotificationCenter defaultCenter];
|
注册通知监听器方法:
?
|
1
2
3
4
5
|
//observer为监听器
//aSelector为接到收通知后的处理函数
//aName为监听的通知的名称
//object为接收通知的对象,需要与postNotification的object匹配,否则接收不到通知
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
|
发送通知的方法:
?
|
1
2
3
4
5
6
7
8
9
10
|
//需要手动构造一个NSNotification对象
- (void)postNotification:(NSNotification *)notification;
//aName为注册的通知名称
//anObject为接受通知的对象,通知不传参时可使用该方法
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
//aUserInfo为将要传递的参数,类型为字典类型
//通知需要传参数时使用下面这个方法,其他同上。
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
|
注销通知监听器方法:
?
|
1
2
3
4
5
6
|
//删除通知的监听器
- (void)removeObserver:(id)observer;
//删除通知的监听器,aName监听的通知的名称,anObject监听的通知的发送对象
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;
//以block的方式注册通知监听器
- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
|
使用情况:
NSNotificationCenter类一般用于一个对象传递事件给另外一个对象,在另一个对象中触发某些方法,可以实现跨视图的交互。我在最近一个月内用到了两次NSNotificationCenter类。
①在对项目进行国际化时,在切换语言时采用通知的方式,使其他界面进行刷新(需要在主线程内)。
②使用SGPagingView时,需要实现pageContentView中的内容在多选状态时,pageTitleView禁止进行切换的功能。看了SGPagingView提供的方法是没有这个的,所以就采用了NSNotificationCenter。在进入多选状态时发一条通知,在退出多选状态时发一条通知(方法比较简陋,如果有更好的方法请不吝赐教)。
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
//注册通知监听器
[NotifyUtil addNotify:NOTIFY_DISABLE_SWITCH Observer:self selector:@selector(disableSwitch) Object:nil];
[NotifyUtil addNotify:NOTIFY_ALLOW_SWITCH Observer:self selector:@selector(allowSwitch) Object:nil];
//调用方法
//禁止pageTitleView进行切换
-(void)disableSwitch{
self.pageTitleView.userInteractionEnabled = NO;
}
//允许pageTitleView进行切换
-(void)allowSwitch{
self.pageTitleView.userInteractionEnabled = YES;
}
//注销通知监听器
- (void) dealloc{
[NotifyUtil removeNotify:NOTIFY_DISABLE_SWITCH Observer:self];
[NotifyUtil removeNotify:NOTIFY_ALLOW_SWITCH Observer:self];
}
|
注:用NotifyUtil对NSNotificationCenter类进行了一个简单的封装,参数基本都一致,就不贴NotifyUtil的代码了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
相关文章
猜你喜欢
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 35
-
2025-05-25 41
-
2025-05-27 15
-
2025-05-25 33
-
2025-06-04 21
热门评论

