DCmodel.h
#import@interface DCtestModel : NSObject@property(copy,nonatomic) NSString *name;- (instancetype)initWithKvo;@end
DCmodel.m
#import "DCtestModel.h"@implementation DCtestModel- (instancetype)initWithKvo { self=[super init]; if (self) { } return self;}@end
直接上代码
//// ViewController.m// DCKvo//// Created by 赵大财 on 16/4/6.// Copyright © 2016年 tshiny. All rights reserved.//#import "ViewController.h"#import "DCtestModel.h"@interface ViewController ()@property(nonatomic,strong) DCtestModel *model;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; _model = [[DCtestModel alloc]initWithKvo]; [_model addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil]; /* NSKeyValueObservingOptionNew 把更改之前的值提供给处理方法 NSKeyValueObservingOptionOld 把更改之后的值提供给处理方法 NSKeyValueObservingOptionInitial 把初始化的值提供给处理方法,一旦注册,立马就会调用一次。通常它会带有新值,而不会带有旧值。 NSKeyValueObservingOptionPrior 分2次调用。在值改变之前和值改变之后 */}-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event { _model.name =@"zhao"; _model.name =@"da";[_model removeObserver:self forKeyPath:@"name"]; _model.name =@"cai";} 当监听的属性改变就会调用这个方法- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ NSLog(@"%@",change); }@end
//运行结果
2016-04-06 18:17:46.692 DCKvo[24931:549533] {
kind = 1; new = zhao;}2016-04-06 18:17:46.692 DCKvo[24931:549533] { kind = 1; new = da;}// cai 已被移除 所以不在监听================================