转自:http://blog.csdn.net/wudizhukk/article/details/8981535

一、KVO

Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。每次指定的被观察的对象的属性被修改后,KVO自动通知相应的观察者。

model中的定义:

@interface StockData : NSObject {
NSString * stockName;
float price;
}
@end
@implementation StockData
@end

controller中使用,记得上一篇怎么说的吗?这里相当于跟模型说,我要收听你的更新广播

- (void)viewDidLoad
{
[super viewDidLoad]; stockForKVO = [[StockData alloc] init];
[stockForKVO setValue:@"searph" forKey:@"stockName"];
[stockForKVO setValue:@"10.0" forKey:@"price"];
[stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL]; myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];
myLabel.textColor = [UIColor redColor];
myLabel.text = [stockForKVO valueForKey:@"price"];
[self.view addSubview:myLabel]; UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0, 0, 100, 30);
[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b]; }

用户单击View中的button调用控制器中的action去更改模型中的数据

-(void) buttonAction
{
[stockForKVO setValue:@"20.0" forKey:@"price"];
}

控制器需要实现的回调,相当于收到广播后我应该做啥事

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"price"])
{
myLabel.text = [stockForKVO valueForKey:@"price"];
}
}

视图dealloc需要取消观察

- (void)dealloc
{
[super dealloc];
[stockForKVO removeObserver:self forKeyPath:@"price"];
[stockForKVO release];
}

二、Notification

通知使用起来非常的简单:

首先定义回调,即发生通知了我应该做啥事。

- (void)callBack{
NSLog(@"我收到通知了!");
}

其次,注册通知,即告诉通知中心,我对啥通知感兴趣

[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(callBack)
name: @"A类通知"
object: nil];

第三,在程序任何一个地方都可以发送通知

- (void)getNotofocation{
NSLog(@"get it.");
//发出通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"A类通知" object:self];
}

当然,也可以在需要的时候取消注册通知。

最新文章

  1. UI第九节——UIProgressView
  2. [USACO 2010 OPEN]SLIED
  3. Failed to issue method call: Unit httpd.service failed to load: No such file or directory.
  4. 第一课JAVA开发环境配置
  5. Count and Say
  6. cookie 换肤
  7. Geek version acm pc^2 direction for user
  8. MyBatis之传入参数——parameterType(转)
  9. 打印十进制数n 递归
  10. JavaFX 简单3D演示样例
  11. ASP.NET WebForm
  12. 由js深拷贝引起的对内存空间的一些思考
  13. github+jekyll个人博客搭建
  14. centos7下kubernetes(3。部署kubernetes)
  15. 个人博客作业Week3--必应词典案例分析
  16. SpringBoot日记——MQ消息队列整合(一)
  17. docker service ps打印出来的错误信息被截断了怎么办?
  18. 软工作业No.5 甜美女孩第三周yep
  19. Hive 简介
  20. Windows 配置Reids集群 Redis Cluster

热门文章

  1. DS12C887实时时钟
  2. 阿里云centos7安装python3.7.4和pip3
  3. netcore之RabbitMQ入门
  4. 有趣的bug——Java静态变量的循环依赖
  5. 如何优雅地停止Spark Streaming Job
  6. bay——安装_RAC11g_LC_测试环境-rehat6+udev.txt
  7. Shell命令-用户用户组管理之id、su
  8. 解决汉化pycharme之后设置打不开的问题
  9. 分析-flag被盗
  10. 浅谈C++ STL stack 容器