IOS 之 通知NSNotificationCenter
来源:互联网 发布:梦想小镇mac同步手机 编辑:程序博客网 时间:2024/05/25 08:12
通知,就是说A观察B的情况.如果B有所改动,就通知A让A知道.这是一种松耦合的通信方式.
有两种方法:
1. NSNotificationCenter通知中心
例子如下:
//构建自定义通知事件和发送//通知的事件名称, 和 参数NSNotification *notification = [NSNotification notificationWithName:@"data changes" object:self];NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];[notificationCenter postNotification:notification];//订阅这个通知后.上边发送的消息,这里才能收到NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];//update是收到通知后执行的方法, subject是上边传送过来的参数[notificationCenter addObserver:self selector:@selector(update:) name:@"data changes" object:subject];
2. NSKeyValueObserving 键值对的方式
手动调用通知
在观察者的类里加上如下代码
//把自身作为观察者加到scribble里//注册@"mark" 为键 scribble为值[scribble addObserver:self forKeyPath:@"mark" opations:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNewcontext:nil];收到通知后执行的方法
//在观察者的代码里加上处理收到通知后的方法- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)changecontext:(void *)context{//如果是来自注册mark的通知就执行并且判断发送通知的来源是否是Scribble类if( [object is KindOfClass:[Scribble class]] && [keyPath isEqualoString:@"mark"] ){//NSKeyValueChangeNewKey是用来获取Scribble里改动的值id mark = [change objectForKey:NSKeyValueChangeNewKey];//..一些处理}}
在被观察者的类里加上
//在scribble类里有变动的地方执行以通知观察者//这里执行完didChangeValueForKey后会发送一条通知执行以下代码[self willChangeValueForKey:@"mark"];....//一些改动[self didChangeValueForKey:@"mark"];
至此,通知差不多就是这,慢慢练练就是熟悉了!
- IOS 之 通知NSNotificationCenter
- iOS开发之通知中心(NSNotificationCenter)
- iOS开发之通知中心(NSNotificationCenter)
- iOS开发之通知中心(NSNotificationCenter)«
- iOS之NSNotificationCenter通知中心使用事项
- iOS开发之NSNotificationCenter(通知)使用介绍
- IOS NSNotificationCenter 通知中心
- IOS NSNotificationCenter 通知中心
- iOS通知中心(NSNotificationCenter)
- iOS通知:NSNotificationCenter
- IOS NSNotificationCenter 通知使用方法
- iOS通知中心NSNotificationCenter
- iOS NSNotificationCenter 通知
- IOS通知中心(NSNotificationCenter)
- iOS Swift NSNotificationCenter 通知
- iOS通知 NSNotificationCenter
- iOS开发之NSNotificationCenter(通知)的使用方法
- iOS开发之NSNotificationCenter(通知)的使用方法
- 入门视频采集与处理(BT656简介) 转
- tslib-1.4编译与安装
- (四)快速排序
- Ubuntu和CentOS中分布式配置Hadoop-2.2.0
- javascript学习(2)——[基础回顾]运算符、表达式、流程控制语句
- IOS 之 通知NSNotificationCenter
- (五)使用最大堆实现优先级队列
- HDU Sequence two 2611 DFS搜索判重
- linux base note(1) (Linux filesystem structure and bash)
- (六)线性选择
- Word快捷键
- (七)线性堆栈
- Remove Element
- Verilog HDL代码书写规范