一,概述
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
二,使用方法
系统框架已经支持KVO,所以程序员在使用的时候非常简单。
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 移除观察
三,实例:
1.新建Person类:
//
// Person.h
// KVOEx
//
// Created by song on 12-11-19.
// Copyright (c) 2012年 song. All rights reserved.
//
#import
@interface Person : NSObject
{
NSString* name;
NSString* age;
}
@property(nonatomic,retain)NSString* name;
@property(nonatomic,retain)NSString* age;
@end
2.在ViewController的.m文件中写:
//
// ViewController.m
// KVOEx
//
// Created by song on 12-11-19.
// Copyright (c) 2012年 song. All rights reserved.
//
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize label;
@synthesize person;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
person=[[Person alloc] init];
[person setValue:@"KVO本来的值" forKey:@"name"];
label=[[UILabel alloc] initWithFrame:CGRectMake(100, 100, 120, 30)];
label.textColor=[UIColor redColor];
label.text=[person valueForKey:@"name"];
[self.view addSubview:label];
UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(120, 150, 50, 30);
[button setTitle:@">" forState:UIControlStateNormal];
[button addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
{
if ([keyPath isEqualToString:@"name"]) {
label.text=[person valueForKey:@"name"];
// [NSThread sleepForTimeInterval:2.0f];
}
}
-(void)change:(id)sender
{
// for (int i=0; i<10; i++) {
// NSString* str=[NSString stringWithFormat:@"%d",i];
// [person setValue:str forKey:@"name"];
// NSLog(@"%d",i);
// }
[person setValue:@"改变KVO的值" forKey:@"name"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)dealloc
{
[person release];
[label release];
[person removeObserver:self forKeyPath:@"name"];
[super dealloc];
}
@end