一,概述
KVC(Key-Value Coding)、KVO(Key-Value Observing)
它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了
二,使用方法
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 移除观察
三,实例:
JJPerson.h
#import <Foundation/Foundation.h>
@interface JJPerson : NSObject {
@public
int age;
@private
NSString *name;
}
@property(nonatomic,retain)NSString *address;
@end
JJPerson.m
#import "JJPerson.h"
@implementation JJPerson
- (void)dealloc
{
[_address release];
[super dealloc];
}
@end
#import "ViewController.h"
#import "JJPerson.h"
@interface ViewController () {
JJPerson *person;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
person = [[JJPerson alloc] init]; // dealloc中释放
[person setValue:@"sun" forKey:@"name"]; // 私有的也可以访问
[person setValue:@"15" forKey:@"age"]; // 整型的通过这种方式赋值
person->age = 11; // 访问public
[person setValue:@"北京" forKey:@"address"];
[person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
[person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
[person addObserver:self forKeyPath:@"address" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
UILabel *la = [[UILabel alloc] init];
la.frame = CGRectMake(10.0, 80.0, 80, 60.0);
la.tag = 99;
la.textColor = [UIColor yellowColor];
la.text = [person valueForKey:@"name"];
la.backgroundColor = [UIColor grayColor];
[self.view addSubview:la];
[la release];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(20.0, 240, 40, 30);
btn.backgroundColor = [UIColor redColor];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
}
- (void)click
{
[person setValue:@"xiaoli" forKey:@"name"]; // 这种方法改变值才有效
[person setValue:@"20" forKey:@"age"];
[person setValue:@"天津" forKey:@"address"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"name"])
{
UILabel *lab = (UILabel *)[self.view viewWithTag:99];
lab.text = [person valueForKey:@"name"];
NSLog(@"old = %@",[change objectForKey:NSKeyValueChangeOldKey]);
NSLog(@"new = %@",[change objectForKey:NSKeyValueChangeNewKey]);
}
if ([keyPath isEqualToString:@"age"]) {
NSLog(@"age = %@",[change objectForKey:NSKeyValueChangeNewKey]);
}
if ([keyPath isEqualToString:@"address"]) {
NSLog(@"address = %@",[change objectForKey:NSKeyValueChangeNewKey]);
}
/**
2015-02-10 13:52:32.595 KVOKVCDemo[928:73952] old = sun
2015-02-10 13:52:32.596 KVOKVCDemo[928:73952] new = xiaoli
2015-02-10 13:52:32.597 KVOKVCDemo[928:73952] age = 20
2015-02-10 13:52:32.597 KVOKVCDemo[928:73952] address = 天津
*/
}
- (void)dealloc
{
[person removeObserver:self forKeyPath:@"name"];
[person removeObserver:self forKeyPath:@"age"];
[person removeObserver:self forKeyPath:@"address"];
[person release];
[super dealloc];
}