标签:
KVO Key,Value,Observing,即键值观察者。它提供了这样一种机制,当指定对象的属性发生改变时,KVO会自动通知相应的观察者。
它与NSNotification不同,键-值观察中并没有所谓的中心对象来为所有观察者提供变化通知。取而代之地,当有变化发生时,通知被直接发送至处于观察状态的对象。
三个步骤:注册观察者,接收变更通知,移除观察者。实例如下:
创建一个工程,创建两个类,一个Weather,一个Station。Weather有一个属性temperNum, ,当temperNum值改变的时候Station接收temperNum值变更。
Weather.h
#import <Foundation/Foundation.h>
@interface Weather : NSObject
@property(nonatomic,assign)NSInteger temperNum;
@end
Station.m
#import "Station.h"
@implementation Station
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"temperNum"]) {
        
        //每当监听的属性temperNum改变时,打印temperNum的当前值和之前值。
        
        NSLog(@"%@  %@",[change objectForKey:@"new"],[change objectForKey:@"old"]);
        
          }
}
@end
ViewController.m
#import "ViewController.h"
#import "Weather.h"//引入头文件
#import "Station.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    Weather * modelWeather =[[Weather alloc]init];//创建对象
    
    Station * modelStation =[[Station alloc]init];
    
      //注册观察者,modelWeather添加了观察者modelWeatherMama,观察temperNum属性。
    
    [modelWeather addObserver:modelStation forKeyPath:@"temperNum" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    
    modelWeather.temperNum=10;//给modelWeather的temperNum属性附一个初值,用一个for循环使得该属性的值改变,每次值改变都会通知监听者。
    
    for (modelWeather.temperNum; modelWeather.temperNum>0; modelWeather.temperNum--) {
        
    }
    
    //移除观察者
    [modelWeather removeObserver:modelStation forKeyPath:@"temperNum"];
    
}
标签:
原文地址:http://blog.csdn.net/lin1986lin/article/details/45056755