您的位置:首页 > 其它

10.通知(NSNotification)

2015-08-01 17:14 239 查看

1.通知的基本概念和用法

通知中心(NSNotificationCenter): 每一个应用程序都有一个通知中心(NSNotificationCenter)实例,专门负责协助不同对象之间的消息通信, 任何一个对象都可以向通知中心发布通知(NSNotification),描述自己在做什么。其他感兴趣的对象(Observer)可以申请在某个特定通知发布时(或在某个特定的对象发布通知时)收到这个通知


通知和代理的选择–>共同点: 利用通知和代理都能完成对象之间的通信(比如A对象告诉D对象发生了什么事情, A对象传递数据给D对象)

不同点: 代理 : 一对一关系(1个对象只能告诉另1个对象发生了什么事情)

通知 : 多对多关系(1个对象能告诉N个对象发生了什么事情, 1个对象能得知N个对象发生了什么事情)

通知(NSNotification)

一个完整的通知一般包含3个属性:
- (NSString *)name; // 通知的名称
- (id)object; // 通知发布者(是谁要发布通知)
- (NSDictionary *)userInfo; // 一些额外的信息(通知发布者传递给通知接收者的信息内容)

1. 初始化一个通知(NSNotification)对象
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo;

2. 发送通知:通知中心(NSNotificationCenter)提供了相应的方法来帮助发布通知
- (void)postNotification:(NSNotification *)notification;
发布一个notification通知,可在notification对象中设置通知的名称、通知发布者、额外信息等
- (void)postNotificationName:(NSString *)aName object:(id)anObject;发布一个名称为aName的通知,anObject为这个通知的发布者
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
发布一个名称为aName的通知,anObject为这个通知的发布者,aUserInfo为额外信息

3. 注册通知:通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(Observer)
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject; observer:监听器,即谁要接收这个通知 aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知
- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block; name:通知的名称 obj:通知发布者 block:收到对应的通知时,会回调这个block queue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行

4. 移除通知:通知中心不会保留(retain)监听器对象,在通知中心注册过的对象,必须在该对象释放前取消注册。否则,当相应的通知再次出现时,通知中心仍然会向该监听器发送消息。因为相应的监听器对象已经被释放了,所以可能会导致应用崩溃
通知中心提供了相应的方法来取消注册监听器
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
一般在监听器销毁之前取消注册(如在监听器中加入下列代码):
- (void)dealloc {
//[super dealloc];  非ARC中需要调用此句
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

5. UIDevice通知
UIDevice类提供了一个单粒对象,它代表着设备,通过它可以获得一些设备相关的信息,比如电池电量值(batteryLevel)、电池状态(batteryState)、设备的类型(model,比如iPod、iPhone等)、设备的系统(systemVersion)通过[UIDevice currentDevice]可以获取这个单粒对象,UIDevice对象会不间断地发布一些通知,下列是UIDevice对象所发布通知的名称常量:
UIDeviceOrientationDidChangeNotification // 设备旋转
UIDeviceBatteryStateDidChangeNotification // 电池状态改变
UIDeviceBatteryLevelDidChangeNotification // 电池电量改变
UIDeviceProximityStateDidChangeNotification // 近距离传感器(比如设备贴近了使用者的脸部)

6. 键盘通知
我们经常需要在键盘弹出或者隐藏的时候做一些特定的操作,因此需要监听键盘的状态,键盘状态改变的时候,系统会发出一些特定的通知
UIKeyboardWillShowNotification // 键盘即将显示
UIKeyboardDidShowNotification // 键盘显示完毕
UIKeyboardWillHideNotification // 键盘即将隐藏
UIKeyboardDidHideNotification // 键盘隐藏完毕
UIKeyboardWillChangeFrameNotification // 键盘的位置尺寸即将发生改变
UIKeyboardDidChangeFrameNotification // 键盘的位置尺寸改变完毕
系统发出键盘通知时,会附带一些跟键盘有关的额外信息(字典),字典常见的key如下:
UIKeyboardFrameBeginUserInfoKey // 键盘刚开始的frame
UIKeyboardFrameEndUserInfoKey // 键盘最终的frame(动画执行完毕后)
UIKeyboardAnimationDurationUserInfoKey // 键盘动画的时间
UIKeyboardAnimationCurveUserInfoKey // 键盘动画的执行节奏(快慢)


2.实例:父亲监听小孩睡觉

main.m文件

Father *father = [[Father alloc] init];
Child *child = [[Child alloc] init];
[[NSRunLoop currentRunLoop] run];


Child.h和Child.m文件

#import <Foundation/Foundation.h>
#define CHILD_WEAK_NOTIFICATION @"child_weak"

@interface Child : NSObject
@property(nonatomic,assign)NSInteger sleep;
@end


#import "Child.h"
@implementation Child

- (id)init {
self = [super init];
if (self != nil) {
_sleep = 100;

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
return self;
}

- (void)timerAction:(NSTimer *)timer {
_sleep -= 2;
NSLog(@"%ld",_sleep);
if (_sleep < 90) {
NSNumber *sleepNum = [NSNumber numberWithInteger:_sleep];
NSDictionary *dic = @{@"sleep":sleepNum};

[[NSNotificationCenter defaultCenter]
postNotificationName:CHILD_WEAK_NOTIFICATION
object:[NSNumber numberWithInteger:_sleep] userInfo:dic];
[timer invalidate];
}
}

@end


Father.h和Father.m文件

#import <Foundation/Foundation.h>
@interface Father : NSObject
@end


#import "Father.h"
#import "Child.h"

@implementation Father

- (id)init {
self = [super init];
if (self != nil) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weekNotification:) name:CHILD_WEAK_NOTIFICATION object:nil];
}
return self;
}

- (void)dealloc {
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] removeObserver:self name:CHILD_WEAK_NOTIFICATION object:nil];
[super dealloc];
}

- (void)weekNotification:(NSNotification *)notification {
NSNumber *num = notification.object;
NSDictionary *dic = notification.userInfo;
NSLog(@"抱起小孩哄哄,_sleep=%@",dic);
}

@end


3.简单传值运用

ViewController.m文件

- (void)dealloc{
//如果添加了观察者,就一定要在这里移除观察者,不移除会造成内存问题
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
//传值的第四种方法,通知中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiAction:) name:@"test" object:nil];
}
- (void)notiAction:(NSNotification *)notification{
NSLog(@"%@",notification.userInfo);
//打印结果:{age = 43;name = "\U5f20\U4e09";
}


SecondViewController.m文件里面的按钮点击事件 , 点击之后返回到ViewController页面

- (void)postNotification{
[self.navigationController popViewControllerAnimated:YES];
NSDictionary *dicn = @{@"name":@"张三",@"age":@"43"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil userInfo:dicn];
}//所需要传的值都装在userInfo字典里面


4.简单监控textField输入内容运用

- (void)dealloc{
//如果添加了观察者,就一定要在这里移除观察者,不移除会造成内存问题
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(100, 200, 150, 50)];
self.textFiled.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.textFiled];
[_textFiled release];//通知中心监听输入框的内容
//四个参数:1.添加监听者的对象,一般都是当前文件按的对象,就是self 2.监听触发方法 3.静听的名,如果对textField进行监听,UITextField提供了专门的常量字符串,127行 4.把要监听的对象放到最后一位,如果只用与传值则是nil
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editChanged) name:UITextFieldTextDidChangeNotification object:self.textFiled];
//之前的做法是添加点击事件进行监听输入框的内容
//[self.textFiled addTarget:self action:@selector(editChanged) forControlEvents:UIControlEventEditingChanged];
}
-(void)editChanged{
NSLog(@"%@",self.textFiled.text);
//这个是用来判断电话号码的正则表达式,正则表达式可以通过自己的语法规则可以用一串表达式判断身份证号等信息,如果需要就百度
NSString *str = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
//用谓词来判断当前输入的文本框内容和正则表达式格式是否吻合
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",str];
//然后进行判断,返回一个BOOL类型的结果
BOOL result = [predicate evaluateWithObject:self.textFiled.text];
if (result) {
NSLog(@"手机号符合条件");
}else {
NSLog(@"手机号有误");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: