Simple use of iOS KVC and KVO
# Import "ViewController. h"
# Import
@ Interface DataModel: NSObject
@ Property (nonatomic, copy) NSString * stockName;
@ Property (nonatomic, assign) float price;
@ End
@ Implementation DataModel
@ End
@ Interface ViewController ()
@ Property UILabel * myLabel;
@ Property UIButton * myButton;
@ Property DataModel * model;
@ End
@ Implementation ViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
Self. model = [[DataModel alloc] init];
[Self. model setValue: @ "searph" forKey: @ "stockName"];
[Self. model setValue: @ "10.0" forKey: @ "price"];
[Self. model addObserver: self forKeyPath: @ "price" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil];
Self. myLabel = [[UILabel alloc] initWithFrame: CGRectMake (130,100,100,100)];
Self. myLabel. layer. masksToBounds = YES;
Self. myLabel. layer. cornerRadius = 50;
Self. myLabel. textAlignment = NSTextAlignmentCenter;
Self. myLabel. textColor = [UIColor cyanColor];
Self. myLabel. backgroundColor = [UIColor grayColor];
Self. myLabel. text = [NSString stringWithFormat: @ "% @", [self. model valueForKey: @ "price"];
[Self. view addSubview: self. myLabel];
Self. myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
Self. myButton. frame = CGRectMake (130,200,100, 30 );
[Self. myButton setTitle: @ "button" forState: UIControlStateNormal];
[Self. myButton addTarget: self action: @ selector (changeValue) forControlEvents: UIControlEventTouchUpInside];
[Self. myButton setBackgroundColor: [UIColor lightGrayColor];
[Self. view addSubview: self. myButton];
}
-(Void) changeValue {
[Self. model setValue: @ "20.0" forKey: @ "price"];
}
-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {
If ([keyPath isw.tostring: @ "price"]) {
Self. myLabel. text = [NSString stringWithFormat: @ "% @", [self. model valueForKey: @ "price"];
}
}
-(Void) dealloc {
[Self. model removeObserver: self forKeyPath: @ "price"];
}
-(Void) didReceiveMemoryWarning {
[Super didReceiveMemoryWarning];
}
@ End