NSNotification即通知,可以实现一个对象发送通知,多个对象接收到通知。
工作流程:
在需要发送通知的类中添加一个通知中心(单例)。
在需要发送通知的类中发送通知,发送通知的对象是self,可定义相应的用户信息,通知名可以是任意定义的字符串,监听通知需要和此通知名匹配。
在需要接收通知的类中添加通知的接收对象,用来监听发出的通知,下面自定义一个接收者的相应方法,方法名封装到上面的接收对象。
最后移除当前对象监听的通知。
举例:在孩子这个类中发送通知,告知孩子脏了,在保姆这个类中接收通知,并实现给孩子洗澡这个方法。
#import "Child.h"
@implementation Child
- (instancetype)init {
if (self = [super init]) {
_cleanValue = 100;
_happyValue = 100;
}
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
return self;
}
- (void)timerAction:(NSTimer *)timer {
_cleanValue--;
_happyValue--;
NSLog(@"cleanValue:%li, happyValue:%li", _cleanValue, _happyValue);
if (_cleanValue == 95) {
//获取到通知中心对象----单例,在内存中只有一个通知中心对象
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//发送通知,带用户信息的通知
//用户信息可由可无,后面被打印出来了
NSDictionary *userInfo = @{
@"name" : @"tengteng",
@"age" : @"22"
};
[center postNotificationName:@"BathNotification" object:self userInfo:userInfo];
}
}
@end
#import "Nanny.h"
#import "Child.h"
@implementation Nanny
//接受到通知后针对此事件要作出响应
- (instancetype)init {
if (self = [super init]) {
//监听通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(cleanValueAction:) name:@"BathNotification" object:nil];
}
return self;
}
- (void)cleanValueAction:(NSNotification *)notification {
//保姆对小孩脏了这个事件的响应
NSLog(@"保姆给小孩洗澡");
//获取到通知的发送者,即小孩,这样才能更改小孩的洁净程度的属性
Child *child = (Child *)notification.object;
//可以通过notification来获取到通知发送者传递的信息
NSLog(@"userInfo:%@", notification.userInfo);
child.cleanValue = 100;
}
- (void)dealloc {
//移除当前对象对所有通知的监听
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end