上节课学习到了KVC和KVO,
而这次说的是通知
通知单是一种发送给一个或者多个观察者,用来通知其在程序中发生某个时间
的消息。
首先初始化,有两种方法
/初始化一个通知(NSNotification)的实例对象
//name:表示通知的名称 object:通知的发起人
NSNotification *notification1 = [NSNotification notificationWithName:@"通知名称1" object:self];
NSNotification *notification2 = [NSNotification notificationWithName:@"通知名称2" object:self userInfo:@{@"content":@"hello world"}];
//通知中心 单例类,拿到通知中心的单例
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//建立通知的发送机制,如下:
// 1.注册监听者,并实现在需要的时候回调方法
// 2.在需要的时候,被监听者的对象去到通知中心发送消息
// 3.在“dealloc”方法中移除通知
- (id)init{
- (id)init{
if (self = [super init]) {
//注册监听者
//1.要去接收通知的对象
//2.接收通知要回调的相应的方法
//3.接收通知的名字
//4.发起通知的对象,一般不需要知道,nil
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"通知名称2" object:nil];
}
return self;
}
2.监听到通知后回调方法
/监听到通知后回调的方法
- (void)notificationAction:(NSNotification *)notification{
NSLog(@"什么是useInfo = %@",notification.userInfo);
}
//移除监听者
- (void)dealloc{
//移除某个通知的监听者
//[[NSNotificationCenter defaultCenter] removeObserver:self name:@"通知名称2" object:nil];
//移除所有通知的监听者
[[NSNotificationCenter defaultCenter]removeObserver:self ];
NSLog(@"aa");
}
1367

被折叠的 条评论
为什么被折叠?



