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 (nonatomiccopy)   NSString * stockName;

@property (nonatomicassignfloat 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 allocinit];

    // 使用KVCstockForKVO赋值

    // [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(1007010030 )];

    myLabel.textColor = [UIColor blackColor];

    myLabel.text =[NSString stringWithFormat:@"%@",[stockForKVO valueForKey:@"price"]] ;

    [self.view addSubview:myLabel];

    

    UIButton * b = [UIButtonbuttonWithType:UIButtonTypeCustom];

    b.frame = CGRectMake(11011010030);

    [b setTitle:@"变价" forState:(UIControlStateNormal)];

    [b setTitleColor:[UIColor blackColorforState:(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

posted @ 2015-05-21 09:27  MacroHong  阅读(120)  评论(0)    收藏  举报