通知(NSNotification)
/*
通知 NSNotification
通过学习KVO,我们发现KVO是一种简单的观察者设计模式,涉及到两个对象,分别是观察者和被观察者.这种方式实质有很大的局限性,那么OC的’Foundation’框架又为开发者提供新的一种观察者设计模式,即通知.
通知,是一种发送给一个或多个观察者,用来通知其在程序中发生了某个事件的消息.Cocoa中的通知机制遵循的是一种广播模式.它是一种程序中事件的发起者或者是处理者和其他想要知道该事件的对象沟通的一种方式.消息的接收者,也就是观察者响应该事件来改变紫的UI,行为或者状态..
*/
初始化一个通知的实例对象
/*
name :表示通知名称
object: 表示通知的发起人
userInfo:表示通知内容
*/
1.NSNotification *notification1=[NSNotification notificationWithName:@"通知名称1" object:self];
2.NSNotification *notification2=[NSNotification notificationWithName:@"通知名称2" object:self userInfo:@{@"content":@"hello world"}];
注意:通知中的内容为字典
建立通知的发送机制
//通知中心(单例类)
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
为什么要讲通知中心???
监听者--->通知中心<---被监听者
也就是发送通知(被监听者)的在通知中心内发送, 接收通知的人(监听者)在通知中心内接收!!!
发送机制的建立步骤:
1.注册相关的监听者,并实现在需要的时候回调方法 (注册)
2.在需要的时候,被监听者的对象去到通知中心发送消息 (回调)
3.在’dealloc’方法中,移除通知 (移除)
现有两个类,一个是observe(监听者)和weather(被监听者)
#import "Observe.h"
@implementation Observe
//注册监听者
-(id)init{
if (self=[super init]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeWeather:) name:@"warn" object:nil];
}
return self;
}
//回调的方法
-(void)changeWeather:(NSNotification *)fiction{
//NSDictionary *dic=fiction.userInfo;
NSLog(@"%@",[fiction userInfo]);
}
//移除监听者
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"warn" object:nil];
}
@end
weather类
#import <Foundation/Foundation.h>
@interface Weather : NSObject
-(void)sendMessage;
@end
#import "Weather.h"
@implementation Weather
-(void)sendMessage{
[[NSNotificationCenter defaultCenter] postNotificationName:@"warn" object:self userInfo:@{@"weather":@"sunny"}];
}
@end
在ViewController.m中
#import "ViewController.h"
#import "Observe.h"
#import "Weather.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
Observe *observe=[Observe new];
Weather *weather=[Weather new];
[weather sendMessage];
}
这里面有个小知识点
这个是通过点击屏幕,也就是当我们点击屏幕是,通知才发送
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
}
但这是在- (void)viewDidLoad之外的函数,而weather为局部变量,所以需要将它变为全局变量
需在ViewController.m中的interface中声明, 如下:
@interface ViewController ()
{
Observe *_observe;
Weather *_weather;
}
@end
整个ViewController.m修改后如下:
#import "ViewController.h"
#import "Observe.h"
#import "Weather.h"
@interface ViewController ()
{
Observe *_observe;
Weather *_weather;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
Observe *observe=[Observe new];
Weather *weather=[Weather new];
//将我们的对象赋给声明的全局变量;
_observe=observe;
_weather=weather;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[_weather sendMessage];
}
@end