Object-C 通知
2015-08-06 12:40
561 查看
通知
通过学习’KVO’,我们发现’KVO’是一种简单的观察者设计模式 ,涉及到两个对象,分别是观察者和被观察者。。这种 方式实质有很大局限性,那么OC的’Foundation’框架又为开发者提供了新的一种观察者设计模式,即’通知’。通知,是一种发送给一个或者多个观察者,用来通知其在程序中发生了某个事件的消息。Cooa中的通知机制遵循的是一种广播的模式。它是一种程序中事件的发起者或者是处理着和其他想要知道该事情的对象沟通的一种方式。消息的接受者,也就是观察者响应该事件来改变自己的UI、行为或者状态。
在OC中,使用’NSNotification’类来表示一个通知。
//初始化一个NSNotification类的实例对象 NSNotification *notification1 = [NSNotification notificationWithName:@"通知名称" object:self]; NSNotification *notification2 = [NSNotification notificationWithName:@"通知名称" object:self userInfo:@{@"content":@"jay is on living"}];
其中: 1.name:表示通知名称,最好英文名,用来识别通知对象 2.object:表示通知的发起人 3.useInfo:表示通知的内容
在现实生活中,我们的邮件都需要由邮局发送给接收人。在OC中也一样,’Foundation’框架定义了一个单例类,通知中心,’NSNotificationCenter’来统一发送通知的实例对象给观察者
//通知中心 单例类,拿到通知中心的单例 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; //通知中心发送通知 [center postNotification:notification1];
//简便写法,通知仲尼直接发送消息 // [center postNotificationName:<#(NSString *)#> object:<#(id)#>] // [center postNotificationName:<#(NSString *)#> object:<#(id)#> userInfo:<#(NSDictionary *)#>]
建立通知发送机制,步骤如下:
1.注册相关监听者,并实现监听收到通知时的方法
2.在需要的时候,被监听的对象去通知中心发送通知。
3.在’dealloc’方法中,移除通知
-(id)init{ if (self = [super init]) { //到通知中心去让自己成为某个通知的监听对象 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:TeacherWithStudentNotification object:nil]; } return self; } -(void)notificationAction:(NSNotification *)notification{ NSLog(@"notification userinfo = %@",notification.userInfo); NSLog(@"上厕所"); } -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self name:TeacherWithStudentNotification object:nil]; }
相关文章推荐
- ABAP 面向对象(Object Orien…
- 黑马程序员--- objective-c的类 对象 方法
- Unlock Object list:CR下清单解锁
- Objective-C相关Category的收集(更新)
- iOS开发之Objective-C(Swift)与JavaScript交互·WebViewJavascriptBridge使用篇
- 关于ObjectOutputStream和ObjectInputStream类的文件的输入输出流操作的心得
- iOS开发者面试必备:10个Objective-C基础面试题
- C#使用ManagementObjectSearcher来获取系统信息时会有out of memory的异常
- 【OC06】类目、延展、协议、计时器(连载八)
- Swift 与 Object-C 项目混搭桥接文件的配置小记
- Objective-C NSPredicate
- PHP Object 转 Array
- WaitForSingleObject等待的时间精度测试
- TypeError:can't use a string pattern on bytes-like object
- TypeError: 'range' object doesn't support item deletion
- IOS学习之Objective-C中的@property和@synthesize用法
- [NSNotificationCenter defaultCenter] addObserver 时 object的意义。
- WaitForSingleObject()函数、WaitForMultipleObject()函数
- Objective-C Expected a type错误
- C#高级编程七十二天----DynamicObject和ExpandoObject