您的位置:首页 > 其它

观察者设计模式——通知

2016-08-16 21:08 246 查看
通知 NSNotification

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:@{@"":@""}];
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: