首页 > 代码库 > KVO初探
KVO初探
KVO全称为key-value oberserving, 源于观察者模式,即key对应的value改变,observer要做出反应。类似Model对Controller发出通知Notification. Notification通常用于响应系统的一些变化,例如键盘出现、消失等。
在数据模型中,将myController设置为观察者,keyPath为myModel的属性,options通常为NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld, context为任意data, 用于传入observeValueForKeyPath:ofObject:change:context:
[myModel addObserver:(NSObject *)myController forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context]
在myController中,实现observeValueForKeyPath:ofObject:change:context:方法来相应value的变化。
//// ViewController.m// KvoTest//// Created by luzheng1208 on 14/12/7.// Copyright (c) 2014年 luzheng. All rights reserved.//#import "ViewController.h"@interface ViewController () { }@property (strong, nonatomic) NSString *name;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.name = @"Xiao Ming"; [self registerForKVO]; //[self willChangeValueForKey:@"name"]; self.name = @"Xiao Hong"; self.name = @"Xiao Li"; //[self didChangeValueForKey:@"name"];}- (void)dealloc { [self unregisterForKVO];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}#pragma mark - KVO- (void)registerForKVO { [self addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];}- (void)unregisterForKVO { [self removeObserver:self forKeyPath:@"name"];}- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"name"]) { NSLog(@"The old value is %@", [change objectForKey:NSKeyValueChangeOldKey]); NSLog(@"The new value is %@", [change objectForKey:NSKeyValueChangeNewKey]); } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; }}@end
其输出为:
2014-12-07 23:02:38.951 KvoTest[19553:2584967] The old value is Xiao Ming2014-12-07 23:02:38.954 KvoTest[19553:2584967] The new value is Xiao Hong2014-12-07 23:02:38.954 KvoTest[19553:2584967] The old value is Xiao Hong2014-12-07 23:02:38.954 KvoTest[19553:2584967] The new value is Xiao Li
上面的例子中未引入Model。
KVO还有手动实现的方法,具体参见blog: http://www.cppblog.com/kesalin/archive/2012/11/17/kvo.html
KVO初探
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。