观察者设计模式——通知

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

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值