KVC & KVO
//
// ViewController.m
// KVO
//
// Created by on 15-4-4.
// Copyright (c) 2015年 Macro. All rights reserved.
//
#import "ViewController.h"
// 定义模型
@interface StockData : NSObject
@property (nonatomic, copy) NSString * stockName;
@property (nonatomic, assign) float price;
@end
@implementation StockData
@end
@interface ViewController (){
// 使用全局变量
StockData *stockForKVO;
UILabel *myLabel;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
// Do any additional setup after loading the view, typically from a nib.
stockForKVO = [[StockData alloc] init];
// 使用KVC给stockForKVO赋值
// [stockForKVO valueForKey:@"stockName"]; 这是设置属性值
[stockForKVO setValue:@"searph"forKey:@"stockName"];
[stockForKVO setValue:@"10.0" forKey:@"price"];
// 添加观察者 stockForKVO是被观察的对象 self是观察者forKeyPath是被观察对象的属性
// 当被观察对象的对应属性值发生变化时,系统会自动通知观察者采取响应
[stockForKVO addObserver:selfforKeyPath:@"price"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:NULL];
myLabel = [[UILabelalloc]initWithFrame:CGRectMake(100, 70, 100, 30 )];
myLabel.textColor = [UIColor blackColor];
myLabel.text =[NSString stringWithFormat:@"%@",[stockForKVO valueForKey:@"price"]] ;
[self.view addSubview:myLabel];
UIButton * b = [UIButtonbuttonWithType:UIButtonTypeCustom];
b.frame = CGRectMake(110, 110, 100, 30);
[b setTitle:@"变价" forState:(UIControlStateNormal)];
[b setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
}
-(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 =[NSStringstringWithFormat:@"%@",[stockForKVOvalueForKey:@"price"]] ;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

浙公网安备 33010602011771号