标签:
KVO 即Key_Value Observing,它是一种观察者设计模式,当被观察者对象的属性被修改后,KVO就会自动通知响应的观察者,观察者就会调用响应的方法
步骤:
1.注册,指定被观察者的属性
2.实现回调方法
3.移除观察者
创建一个Person类
@interface Person : NSObject
{
NSString * name;
NSString *pid;
}
@end
在ViewController.m文件
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property(nonatomic,retain)Person *dm;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.dm=[[Person alloc]init];
[_dm setValue:@"daren" forKey:@"name"];
[_dm setValue:@"1" forKey:@"pid"];
//注册观察者
[_dm addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
UILabel *testLabel =[[UILabel alloc]init];
testLabel.frame=CGRectMake(20, 20, 100, 30);
testLabel.backgroundColor=[UIColor clearColor];
testLabel.tintColor=[UIColor blackColor];
testLabel.tag=1001;
testLabel.text=[_dm valueForKey:@"name"];
[self.view addSubview:testLabel];
UIButton * button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(20, 100, 100, 70);
[button setTitle:@"测试" forState:UIControlStateNormal];
[button addTarget:self action:@selector(testPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
//按钮响应事件
- (void)testPressed{
[_dm setValue:@"wangzi" forKey:@"name"];
}
//当被观察者的属性改变时,系统就会通知观察者,并且会这行下列这个方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
UILabel * label=(UILabel *)[self.view.superview viewWithTag:1001];
if ([keyPath isEqualToString:@"name"]) {
label.text=[_dm valueForKey:@"name"];
}
}
-(void)dealloc{
[super dealloc];
//移除观察者
[_dm removeObserver:self forKeyPath:@"name"];
[_dm release];
}
标签:
原文地址:http://www.cnblogs.com/wangbinbin/p/4790980.html