观察者设计模式——通知
2016-08-16 21:08
246 查看
通知 NSNotification
OC中的KVO是一种简单的观察者设计模式,涉及到两个对象,分别是观察者和被观察者。这种方式实质有很大的局限性。OC的Foundation框架为开发者提供了新的一种观察者设计模式,即通知。
通知:一种发送给一个或者多个观察者,用来通知其在程序中发生了某个事件的消息。Cocoa中的通知机制遵循的是一种广播模式。它是一种程序中事件的发起者或者是处理者和其它想要知道该事件的对象沟通的一种方式。消息的接收者,也就是观察者响应该事件来改变自己的UI、行为或者状态。
初始化一个通知(NSNotification)的实例对象:
其中name表示的是通知名称,object表示通知发起人(对象),userInfo:表示通知内容
创建通知中心(NSNotificationCenter)对象
建立通知发送机制:
其中addObserver是添加监听者,selector是选择回调方法,name是通知名称,Object表示通知的目标。
运行结果:
OC中的KVO是一种简单的观察者设计模式,涉及到两个对象,分别是观察者和被观察者。这种方式实质有很大的局限性。OC的Foundation框架为开发者提供了新的一种观察者设计模式,即通知。
通知:一种发送给一个或者多个观察者,用来通知其在程序中发生了某个事件的消息。Cocoa中的通知机制遵循的是一种广播模式。它是一种程序中事件的发起者或者是处理者和其它想要知道该事件的对象沟通的一种方式。消息的接收者,也就是观察者响应该事件来改变自己的UI、行为或者状态。
初始化一个通知(NSNotification)的实例对象:
NSNotification *notification1 = [NSNotification notificationWithName:@"nontification_One" object:self]; //或者 NSNotification *notification2 = [NSNotification notificationWithName:@"nontification_Two" object:self userInfo:@{@"content":@"Hello world!"}];
其中name表示的是通知名称,object表示通知发起人(对象),userInfo:表示通知内容
创建通知中心(NSNotificationCenter)对象
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
建立通知发送机制:
//.m实现文件(观察者类中实现) //重写初始化方法 -(id)init{ if(self = [super init]) { //1.注册监听者 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"WeatherAndPhoneUser" object:nil]; } return self; }
其中addObserver是添加监听者,selector是选择回调方法,name是通知名称,Object表示通知的目标。
//回调方法 -(void)notificationAction:(NSNotification *)notification{ NSDictionary *dic = notification.userInfo; NSL(@"%@",dic); }
//移除监听者 -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; }
//通知发送(一般在被观察者类中实现) -(void)sendMessage{ [NSNotificationCenter default]postNotificationName:"WeatherAndPhoneUser" object:self userInfo:@{@"":@""}]; }
运行结果:
相关文章推荐
- ios开发中的基本设计模式(代理,观察者,MVC,单例,策略,工厂,MVVM,原型,Target-Action,通知(notification)机制)
- 一个采取数据后的预警通知的设计----观察者模式的变通
- Cocos中的观察者设计模式与通知机制
- Android中设计模式--观察者模式(一对多的关系,对象改变时依赖者都会收到通知)
- Java设计模式之观察者模式的应用--简单的事件通知工具
- 设计模式(二):自己动手使用“观察者模式”实现通知机制
- Cocos中的观察者设计模式与通知机制
- 探究观察者设计模式
- 设计模式与泡mm的关系之Observer观察者模式及再思考
- 乐在其中设计模式(C#) - 观察者模式(Observer Pattern)
- 乐在其中设计模式(C#) - 观察者模式(Observer Pattern)
- 设计模式随笔系列:气象站的故事-观察者模式(Observer)[原]
- 利用观察者模式设计仿真器内核接口
- .NET中的设计模式五:观察者模式
- 设计模式之Observer观察者模式
- 认识观察者模式(设计模式)[转载]
- 设计模式学习笔记(二十一)——Observer观察者
- 设计模式理解 - 伟大的【Observer 观察者模式】
- Java设计模式之Observer(观察者)模式
- 设计模式之观察者模式 (原创)