add observer的两个用法
2016-01-15 15:26
281 查看
addObserver有两种时候会调
一种是广播
发广播的方法:
监听广播:
第二种是KVO
添加默认的响应回调方法
监听释放
一种是广播
发广播的方法:
[[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATIONNAME object:nil userInfo:userinfo];//userinfo是个dictionary
监听广播:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectorName:) name:NOTIFICATIONNAME object:nil]; //收到广播要做的事件 -(void)selectorName:(NSNotification *)notification{ NSDictionary *dic= [notification userInfo]; }
第二种是KVO
per= [[Person alloc] init]; //per是全局的 [per setValue:@"annie" forKey:@"name"]; [per setValue:@"20" forKey:@"age"]; [per addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL]; //此处的self是谁来监听per的变化,谁来监听在谁那里调回调方法
添加默认的响应回调方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { //object为per ,keyPath为age if([keyPath isEqualToString:@"age"]) { //do something } }
监听释放
- (void)dealloc { [per removeObserver:self forKeyPath:@"age"]; //kvo的 [NSNotificationCenter defaultCenter]removeObserver:self]; //广播的 [per release]; //[super dealloc]; }
相关文章推荐
- fread
- UML类图与对象图
- 从此不再惧怕URI编码:JavaScript及C# URI编码详解
- UIView属性clipsTobounds的应用
- mvc dropdown
- 1丶验证码无判断
- ssh-keygen和ssh-copy-id实现SSH无密码登录
- sqoop使用经验总结及问题汇总
- 学习笔记---mem族函数
- nginx下502和504错误的解决办法
- leveldb代码阅读(17)——流程分析:写数据(详细版本)
- Android Activity切换动画(解决back键后退失效问题)
- iOS开发UI篇—CALayer简介
- EXT实现表格斑马线
- js this
- 学java心得体会
- Android持久化技术之文件的读取与写入实例详解
- C++多态实现及原理
- Android 沉浸式状态栏攻略 让你的状态栏变色吧
- Android HttpsURLConnection get、post 访问网络